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

 

posted @ 2016-11-26 19:34  Newsteinwell  阅读(4007)  评论(0编辑  收藏  举报