溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python實現(xiàn)簡單文本字符串處理的方法

發(fā)布時間:2020-10-03 11:08:07 來源:腳本之家 閱讀:127 作者:Lovephysics 欄目:開發(fā)技術

本文實例講述了Python實現(xiàn)簡單文本字符串處理的方法。分享給大家供大家參考,具體如下:

對于一個文本字符串,可以使用Python的string.split()方法將其切割。下面看看實際運行效果。

mySent = 'This book is the best book on python!'
print mySent.split()

輸出:

['This', 'book', 'is', 'the', 'best', 'book', 'on', 'python!']

可以看到,切分的效果不錯,但是標點符號也被當成了詞,可以使用正則表達式來處理,其中分隔符是除單詞、數(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)在得到了一系列詞組成的詞表,但是里面的空字符串需要去掉。

可以計算每個字符串的長度,只返回大于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)句子中的第一個字母是大寫的。我們需要同一形式,把大寫轉(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

輸出:

復制代碼 代碼如下:
['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']

更多關于Python相關內(nèi)容可查看本站專題:《Python字符串操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》

希望本文所述對大家Python程序設計有所幫助。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI