I'm pretty new to python so please forgive me,if this is really obvious. I would like to replace all the words in file with alternative words based on a dictionary ( or dictionary file). I've been through a number of other posts and this code ( below) works quite well. However, it will also replace substrings.
text = "strings.txt"
fields = {"Cat": "Hello", "Hat": "Goodbye"}
for line in fileinput.input(text, inplace=True):
line = line.rstrip()
if not line:
continue
for f_key, f_value in fields.items():
if f_key in line:
line = line.replace(f_key, f_value)
print (line)
So, caterpillar will become Helloerpillar and hatemonger will become Goodbyemonger. I would like substrings to be left alone, so only the full words will be replaced. Can anyone advise me on how to do this?
Also.... This is less important but I have also tried to get the script to read the dictionary from a separate file. This isn't so important but it would be nice to have.
I have tried to modify the script in the following way without luck.
import json
with open('dictionary.txt') as f:
data = f.read()
text = "strings.txt"
fields = data
for line in fileinput.input(text, inplace=True):
line = line.rstrip()
if not line:
continue
for f_key, f_value in fields.items():
if f_key in line:
line = line.replace(f_key, f_value)
print (line)
any advice that you could provide on either of these problems ( especially the first) would be greatly appreciated.
Thanks