In python, I am trying to use re.sub with a dict to replace multi "exact" substrings. The following is a sample example.
import re
words = "apple pineapple cat category data old_data"
dic = {"apple":"apple_new", "cat":"cat_new", "data":"data_new"}
pattern = re.compile("|".join(dic.keys()))
new_words = re.sub(pattern, lambda m: dic[m.group(0)], words)
The result is :
apple_new pineapple_new cat_new cat_newegory data_new old_data_new
The result I expected is :
apple_new pineapple cat_new category data_new old_data
What should I do? I have tried Replace exact substring in python methods (r"\b...\b")
new_words2 = re.sub(r"\bapple\b", "apple_new", words)
It can reach my goals. But in my real project, I have to replace about 100 patterns at once. So I hope can use dict with r"\bapple\b"
If you know how to do, please tell me, thanks.