I have a dictionary and string like :
d = {'ASAP':'as soon as possible', 'AFAIK': 'as far as I know'}
s = 'I will do this ASAP, AFAIK. Regards, X'
I want to replace the values of dict with the keys of the dict in the string and return
I will do this <as soon as possible>, <as far as I know>. Regards, X.
I use
pattern = re.compile(r'\b(' + '|'.join(d.keys())+r')\b')
result=pattern.sub(lambda x: '<'+d[x.group()]+'>',s)
print"result:%s" % result
I have a dictionary like:
{'will you wash some pants for me please :-)': 'text'}
The smiley is causing an error. How do I change my regular expression to suit any characters like smileys?
You need to escape any regular expression metacharacters with re.escape()
:
pattern = re.compile(r'\b(' + '|'.join(map(re.escape, d)) + r')\b')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With