I am trying to replace each word after .
in the txt file below:
line1
line2
field: [orders.cancelled,orders.delivered,orders.reached
orders.pickup,orders.time]
some line
some line
I have a dictionary:
d = {'cancelled':'cancelled_at', 'deliver':'xxx'}
I am running the following code. However, I am getting the results for partial match i.e
I see the new file has the following words
field: [orders.cancelled_at, orders.xxxed ..........
here from the word delivered the program is still replacing the first 7 words(deliver) and adding 'ed' in the end. I am not sure why
with open('list.txt', 'r') as g:
text = g.read()
for k in d:
before = f'.{k}'
after = f'.{d[k]}
#print(before)
#print(after)
text = text.replace(before, after)
#print(text)
with open('new_list.txt', 'w') as w:
w.write(text)
I also tried this one and I get the same results
import re
with open('list.txt', 'r') as f:
text = f.read()
for k in d:
before = f'.{k}(?!=\w)'
print(before)
after = f'.{d[k]}'
print(after)
text = re.sub(before, after, text)
with open('new_list.txt', 'w') as w:
w.write(text)