Żeby to był poprawny regexp, to musisz to napisać tak:
from re import escape
s = r'This is a first \thing to replace and this is a second \thing2 to replace, thing\thing'
things = {
r'\thing': "REPLACED1",
r'\thing2': "REPLACED2"
}
for thing, value in things.items():
s = re.sub(r'\b' + escape(thing) + r'\b', value, s)
Teraz pojawia się pytanie, co się ma stać, jeśli dam np taki string: s = r'This is \thing and thing\thing'
? Czy ma zostać zamienione na r'This is REPLACED1 and thingREPLACED1'
? Czy ma zostać s = r'This is REPLACED1 and thing\thing'
? Oraz czy ma podmienić \things
?
Jeśli to pierwsze, to jesteś w domu. Jeśli to drugie, to musisz zamienić pierwsze \b
, tak że:
import re
from re import escape
s = r'This is a first \thing to replace and this is a second \thing2 to replace, thing\thing also \things'
things = {
r'\thing': "REPLACED1",
r'\thing2': "REPLACED2"
}
for thing, value in things.items():
s = re.sub(r'(?<=\s)' + escape(thing) + r'(?=\s)', value, s)
Pojawia się też pytanie czy powinno podmienić np (\thing)
, ale to chyba temat na inną rozmowę.