替換句子中的多個不同的詞—— python 實現


對一個句子中的多處不同的詞的替換,可以采用依次將句子中的每個詞分別和詞典進行匹配,匹配成功的進行替換來實現,可是這種方法直覺上耗時就很長,對於一個篇幅很長的文檔,會花費很多的時間,這里介紹一種可以一次性替換句子中多處不同的詞的方法,代碼如下:

#!/usr/bin/env python # coding=utf-8
import re def multiple_replace(text, idict): rx = re.compile('|'.join(map(re.escape, idict))) def one_xlat(match): return idict[match.group(0)] return rx.sub(one_xlat, text) idict={'3':'2', 'apples':'peaches'} textBefore = 'I bought 3 pears and 4 apples' textAfter= multiple_replace(textBefore,idict) print (textBefore) print (textAfter)

運行結果為:

 

I bought 3 pears and 4 apples
I bought 2 pears and 4 peaches

 

可見,multiple_replace() 函數的返回值也是一個字符串(句子),且一次性將 "3" 替換為 "2",將 "apples" 替換為 "peaches"

參考: http://blog.csdn.net/huludan/article/details/50925735

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM