Python實現簡單文本字串處理的方法,python字串

來源:互聯網
上載者:User

Python實現簡單文本字串處理的方法,python字串

本文執行個體講述了Python實現簡單文本字串處理的方法。分享給大家供大家參考,具體如下:

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

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

輸出:

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

可以看到,切分的效果不錯,但是標點符號也被當成了詞,可以使用Regex來處理,其中分隔字元是除單詞、數字外的任一字元串。

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', '']

現在得到了一系列片語成的詞表,但是裡面的Null 字元串需要去掉。

可以計算每個字串的長度,只返回大於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']

最後,發現句子中的第一個字母是大寫的。我們需要同一形式,把大寫轉化為小寫。Python內嵌的方法,可以將字串全部轉化為小寫(.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']

下面來看一封完整的電子郵件:

內容

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

輸出:
複製代碼 代碼如下:['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']

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.