Python實(shí)現(xiàn)簡(jiǎn)單文本字符串處理的方法
本文實(shí)例講述了Python實(shí)現(xiàn)簡(jiǎn)單文本字符串處理的方法。分享給大家供大家參考,具體如下:
對(duì)于一個(gè)文本字符串,可以使用Python的string.split()方法將其切割。下面看看實(shí)際運(yùn)行效果。
mySent = 'This book is the best book on python!' print mySent.split()
輸出:
['This', 'book', 'is', 'the', 'best', 'book', 'on', 'python!']
可以看到,切分的效果不錯(cuò),但是標(biāo)點(diǎn)符號(hào)也被當(dāng)成了詞,可以使用正則表達(dá)式來處理,其中分隔符是除單詞、數(shù)字外的任意字符串。
import re
reg = re.compile('\\W*')
mySent = 'This book is the best book on python!'
listof = reg.split(mySent)
print listof
輸出為:
['This', 'book', 'is', 'the', 'best', 'book', 'on', 'python', '']
現(xiàn)在得到了一系列詞組成的詞表,但是里面的空字符串需要去掉。
可以計(jì)算每個(gè)字符串的長度,只返回大于0的字符串。
import re
reg = re.compile('\\W*')
mySent = 'This book is the best book on python!'
listof = reg.split(mySent)
new_list = [tok for tok in listof if len(tok)>0]
print new_list
輸出為:
['This', 'book', 'is', 'the', 'best', 'book', 'on', 'python']
最后,發(fā)現(xiàn)句子中的第一個(gè)字母是大寫的。我們需要同一形式,把大寫轉(zhuǎn)化為小寫。Python內(nèi)嵌的方法,可以將字符串全部轉(zhuǎn)化為小寫(.lower())或大寫(.upper())
import re
reg = re.compile('\\W*')
mySent = 'This book is the best book on python!'
listof = reg.split(mySent)
new_list = [tok.lower() for tok in listof if len(tok)>0]
print new_list
輸出為:
['this', 'book', 'is', 'the', 'best', 'book', 'on', 'python']
下面來看一封完整的電子郵件:
內(nèi)容
Hi Peter, With Jose out of town, do you want to meet once in a while to keep things going and do some interesting stuff? Let me know Eugene
import re
reg = re.compile('\\W*')
email = open('email.txt').read()
list = reg.split(email)
new_txt = [tok.lower() for tok in list if len(tok)>0]
print new_txt
輸出:
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python字符串操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python保留小數(shù)函數(shù)的幾種使用總結(jié)
本文主要介紹了python保留小數(shù)函數(shù)的幾種使用總結(jié),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
Python?return函數(shù)返回值類型和幫助函數(shù)使用教程
這篇文章主要為大家介紹了Python?return函數(shù)返回值類型和幫助函數(shù)使用教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
Python腳本實(shí)現(xiàn)自動(dòng)刪除C盤臨時(shí)文件夾
在日常使用電腦的過程中,臨時(shí)文件夾往往會(huì)積累大量的無用數(shù)據(jù),占用寶貴的磁盤空間,下面我們就來看看Python如何通過腳本實(shí)現(xiàn)自動(dòng)刪除C盤臨時(shí)文件夾吧2025-01-01

