码迷,mamicode.com
首页 > 编程语言 > 详细

替换句子中的多个不同的词—— python 实现

时间:2016-11-26 21:02:02      阅读:355      评论:0      收藏:0      [点我收藏+]

标签:match   python   ref   tar   color   size   函数   blog   实现   

对一个句子中的多处不同的词的替换,可以采用依次将句子中的每个词分别和词典进行匹配,匹配成功的进行替换来实现,可是这种方法直觉上耗时就很长,对于一个篇幅很长的文档,会花费很多的时间,这里介绍一种可以一次性替换句子中多处不同的词的方法,代码如下:

#!/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

 

替换句子中的多个不同的词—— python 实现

标签:match   python   ref   tar   color   size   函数   blog   实现   

原文地址:http://www.cnblogs.com/Newsteinwell/p/6105008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!