Python進行文字處理

2022-08-24 08:09:14 字數 2906 閱讀 4563

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

mysent = '

this book is the best book on python!

'print mysent.split()

輸出:

['

this

', '

book

', '

is', '

the', '

best

', '

book

', '

on', '

python!

']

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

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

', '']

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

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

meet once in a while to keep things

going and do some interesting stuff?

let me know

eugene

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

']

awk進行文字處理

1 awk的內建變數 awk 所內建的字段變數及其涵意如下 字段變數 含義 0 一字串,其內容為目前 awk 所讀入的資料行.1 0 上第乙個欄位的資料.2 0 上第二個欄位的資料.其餘類推 內建變數 含義nf number of fields 為一整數,其值表 0上所存在的字段數目.nr numb...

使用awk進行文字處理

有過大文字處理經歷的朋友一定都知道awk,這是一種指令碼語言,對於處理一定格式的資料還是很方便使用的。下面介紹一下awk的常用方法。如果想系統學習,請看 1 awk的內建變數 awk 所內建的字段變數及其涵意如下 字段變數 含義 0 一字串,其內容為目前 awk 所讀入的資料行.1 0 上第乙個欄位...

shell sed多行文字處理

本案例要求使用sed工具來完成下列任務操作 修改主機名配置檔案 修改hosts檔案,新增兩條對映記錄 192.168.4.5 與 svr5.tarena.com svr5,還有119.75.217.56與www.baidu.com sed工具的多行文字處理操作 i 在指定的行之前插入文字 a 在指定...