替换句子中的多个不同的词—— python 实现,,对一个句子中的多处不
替换句子中的多个不同的词—— python 实现,,对一个句子中的多处不
对一个句子中的多处不同的词的替换,可以采用依次将句子中的每个词分别和词典进行匹配,匹配成功的进行替换来实现,可是这种方法直觉上耗时就很长,对于一个篇幅很长的文档,会花费很多的时间,这里介绍一种可以一次性替换句子中多处不同的词的方法,代码如下:
#!/usr/bin/env python# coding=utf-8import redef 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 applesI bought 2 pears and 4 peaches
可见,multiple_replace() 函数的返回值也是一个字符串(句子),且一次性将 "3" 替换为 "2",将 "apples" 替换为 "peaches"
参考:http://blog.csdn.net/huludan/article/details/50925735
替换句子中的多个不同的词—— python 实现
相关内容
- 通过线程控制python程序运行一定时间,,<span styl
- Python绘制wav文件音频图(静态)[matplotlib/wave],,#!/usr/bin
- python3-特征值,特征向量,逆矩阵,,import num
- python小白之paramiko(1),,楼主python小白
- Python赋值运算符,,以下假设变量a为10
- 资深程序员告诉你为什么要用Python3而不是Python2,,经常
- 【python】-递归,局部变量与全局变量,,1.必须有一个明
- Python判断网络是否可以访问,,import ur
- python numpy访问行列元素的方法,,import num
- python模块之os_sys_动态导入_包,,#!/usr/bin
评论关闭