【发布时间】:2017-04-19 09:35:26
【问题描述】:
您好,我正在尝试使用该函数一次性替换多个单词:
def multiple_replace(text, dict):
regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
但我的问题是,如果我有一本字典:
dict = { 'hello1': 'hi', 'hello111' : 'GoodMorning', 'world' : 'earth' }
我试试
s = " hello111 world"
multiple_replace(s, dict)
函数匹配 hello1 而不是 hello111 符合预期
如果你们有任何线索,那就太好了!
我想反转搜索以确保函数从最长的键开始,因为我的键已排序,但这可能不是最好的方法。
【问题讨论】:
-
使用单词边界 -
regex = re.compile(r"\b(%s)\b" % "|".join(map(re.escape, dict.keys())))。或者按长度按降序对键进行排序,并使用非单词边界方法。 -
尝试使用
regex = re.compile("(%s)" % "|".join(sorted(dict, key=lambda k: len(k), reverse=True)))- 可以这样工作吗?
标签: python regex string replace regular-language