替换句子中的多个不同的词—— 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