我有一个键值对的python字典,我想用它们对应的值替换字符串中的一些词,这些词是字典中的键。
我尝试了一些在线找到的代码。这是示例:
test_dict = {'a/a': 'result1', "a/a b/b c/c": "result2"}
sentence = "<<a/a>> something <<a/a b/b c/c>> something"
result = multiple_replace(test_dict, sentence)
def multiple_replace(dict, text):
regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
我预计结果是<<result1>> something <<result2>> something
实际输出为<<result1>> something <<result1 b/b c/c>> something