【发布时间】: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