国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2020-01-04 16:03:11
字體:
供稿:網(wǎng)友

本文實例講述了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!']

可以看到,切分的效果不錯,但是標(biāo)點符號也被當(dāng)成了詞,可以使用正則表達式來處理,其中分隔符是除單詞、數(shù)字外的任意字符串。

import rereg = 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 rereg = 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 rereg = 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 tomeet once in a while to keep thingsgoing and do some interesting stuff?Let me knowEugene
import rereg = 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

輸出:

復(fù)制代碼 代碼如下:
['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程序設(shè)計有所幫助。


注:相關(guān)教程知識閱讀請移步到python教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 金湖县| 唐河县| 葵青区| 明光市| 阿拉善左旗| 石狮市| 岫岩| 安宁市| 上杭县| 建始县| 略阳县| 彝良县| 华宁县| 丰宁| 合山市| 邳州市| 涞源县| 台湾省| 黄梅县| 长子县| 永昌县| 繁昌县| 黑龙江省| 林芝县| 新河县| 新沂市| 绥化市| 宁河县| 房产| 多伦县| 阿荣旗| 长子县| 临高县| 兴山县| 隆尧县| 美姑县| 蚌埠市| 阳江市| 凤山县| 彰化市| 武乡县|