【问题标题】:searching and replacing words with upper and lower cases of the same word用相同单词的大小写搜索和替换单词
【发布时间】:2018-09-25 12:33:12
【问题描述】:

此脚本的重点是替换多个单词字符串,无论单词以小写字母还是大写字母开头。

代码示例:

import re
from re import sub

def word_replace(text, replace_dict):
    rc = re.compile(r"[A-Za-z_]\w*")
def translate(match):
    word = match.group(0) 
    return replace_dict.get(word, word)
return rc.sub(translate, text)

old_text = """Bob: say why don't you play ball
jeff: i have no idea
bob: well maybe you should """

replace_dict = {
"Bob" : 'bob baller',
"debug" : "fix",
'ship': 'boat'
 }

我得到的是:

bob baller: say why don't you play ball
jeff: i have no idea
bob: well maybe you should 

我想从文本中得到“Bob”和“bob”,然后将它们都替换为 bob Baller。

为了进一步澄清这个问题,我要做的是替换单词“bob”(或replace_dict中的任何单词),如果它是大写或小写的。

【问题讨论】:

    标签: python python-3.x replace


    【解决方案1】:

    用像这样的附加参数编译你的正则表达式

    re.compile("你的正则表达式放在这里", re.IGNORECASE)

    编辑 1:

    好的,事实证明,由于双引号和单引号的使用不一致,您的 replace_dict 格式不正确。 这是工作代码和预期输出:

    bob_baller.py

    import re
    
    def word_replace(text, replace_dict):
        rc = re.compile(r"[A-Za-z_]\w*")
    
        def translate(match):
            word = match.group(0).lower()
            print(word)
            return replace_dict.get(word, word)
    
        return rc.sub(translate, text)
    
    old_text = """Bob: say why don't you play ball
    jeff: i have no idea
    bob: well maybe you should """
    
    replace_dict = {
        "bob" : "bob baller",    # Everything is double quoted
        "debug" : "fix",
        "ship": "boat"
     }
    
    output = word_replace(old_text, replace_dict)
    print(output)
    
    $ python bob_baller.py
    bob baller: say why don't you play ball
    jeff: i have no idea
    bob baller: well maybe you should 
    

    【讨论】:

      【解决方案2】:

      您可以将 replace_dict 键转换为小写,然后匹配两个单词并替换。就像鲍勃和鲍勃的比赛一样。

      【讨论】:

      • 我在想一些类似的事情,但是(这实际上是我没有把它放在我原来的帖子中的错)我打算使用这个代码来查看更大的文本区域(old_text)和在我的 replace_dic 中使用大量单词,试图消除输入所有大写、小写、前缀和后缀的过程中的乏味。无论如何,谢谢你的回答最糟糕的事情我会用这个。
      • 你可以这样写 re.compile(r"[A-Za-z_]\w*", re.I)。它会忽略大小写
      猜你喜欢
      • 2014-06-03
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多