【问题标题】:Replacement of multiple substrings with re.IGNORECASE用 re.IGNORECASE 替换多个子字符串
【发布时间】:2019-11-20 18:31:18
【问题描述】:

我想用 Python 字典替换文档中的单词,并且我想实现不区分大小写的替换。 就像我们有一个字符串:

    string = 'spam fOo bar foo bar spam fOO'

还有一本字典:

    substitutions = {"foo": "TEST", "bar": "BAR"}

我想要得到的结果:

    'spam TEST bar TEST bar spam TEST'

即所有的“foo”词都会被替换,不管大写还是小写。

为此我找到了下一个函数:

    def replace(string, substitutions):
        regex = re.compile('|'.join(map(re.escape, substitutions)))
        return regex.sub(lambda match: substitutions[match.group(0)], string)

它返回我:

    'TEST spam fOo BAR TEST BAR spam fOO'

即只有完全匹配被替换。如果我将 re.IGNORECASE 作为 re.compile() 的标志 - 没有任何变化。

【问题讨论】:

    标签: python regex python-3.x dictionary


    【解决方案1】:

    添加re.IGNORECASE并尝试

      ... substitutions[match.group().lower()] ...
    

    因为 subtitutions[match.group()] 在匹配为“fOo”时找不到相关值

    【讨论】:

      猜你喜欢
      • 2017-12-06
      • 2016-09-10
      • 2020-10-29
      • 2011-09-01
      • 2021-06-13
      • 2011-12-01
      • 2015-11-09
      • 1970-01-01
      相关资源
      最近更新 更多