zoukankan      html  css  js  c++  java
  • 替换句子中的多个不同的词—— 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

     

  • 相关阅读:
    使用DataReader
    使用Dataset
    Command
    Ado.net对象
    集合数据源
    Label 表达式绑定
    输出二进制图像
    Application 可以存储全局变量
    字符串处理
    ?:叫条件运算符
  • 原文地址:https://www.cnblogs.com/Newsteinwell/p/6105008.html
Copyright © 2011-2022 走看看