I have a python dictionary of key, value pairs and I want to replace some words in a string which are the keys in the dictionary with their corresponding values.
I have tried some code which are found online.Here is the example:
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)
I expected the result to be <<result1>> something <<result2>> something
The actual output is <<result1>> something <<result1 b/b c/c>> something