對乙個句子中的多處不同的詞的替換,可以採用依次將句子中的每個詞分別和詞典進行匹配,匹配成功的進行替換來實現,可是這種方法直覺上耗時就很長,對於乙個篇幅很長的文件,會花費很多的時間,這裡介紹一種可以一次性替換句子中多處不同的詞的方法,**如下:
#!/usr/bin/env python
#coding=utf-8
import
redef
multiple_replace(text, idict):
rx = re.compile('|'
.join(map(re.escape, idict)))
defone_xlat(match):
return
idict[match.group(0)]
return
rx.sub(one_xlat, text)
idict=
textbefore = '
'textafter=multiple_replace(textbefore,idict)
(textbefore)
print (textafter)
執行結果為:
i bought 2 pears and 4 peaches
參考:
linux sed 批量替換多個檔案中的字串
一 linux sed 批量替換多個檔案中的字串 sed i s oldstring newstring g grep oldstring rl yourdir 例如 替換 home下所有檔案中的www.bcak.com.cn為bcak.com.cn sed i s www.bcak.com.cn ...
第4題 顛倒乙個句子中的詞的順序
題目 顛倒乙個句子中的詞的順序,比如 i am a student 顛倒後變成 student a am i 此題緊接著第3題,不過要把第3題的函式做一定修改 include include char reverse char str,int n int end n 1 int start 0 wh...
linux批量替換多個檔案中的相同字段
最近跑的程式都有很多個case,各個case之間除了輸入資料檔案不同,其他 都一樣,有時候要修改模式的解析度,乙個case還好,幾十個case挨個改太費時間了。於是刷各種部落格和解釋發現sed命令很方便 sed s resolution 0.1 resolution 1 g i grep wrl r...