Replace words in a file
I need to read in a text file, replace selected words and write the changed text back out to a file. Is there an easy way with Python?
sneekula
Nearly a Posting Maven
2,427 posts since Oct 2006
Reputation Points: 961
Solved Threads: 212
Thanks ghostdog!
I will have to play with those code ideas. I need to replace several different words in the text file.
sneekula
Nearly a Posting Maven
2,427 posts since Oct 2006
Reputation Points: 961
Solved Threads: 212
Here is an example, where the target and replacement words are in a dictionary. The Python module re is used to do the gruntwork ...
# read a text file, replace multiple words specified in a dictionary
# write the modified text back to a file
import re
def replace_words(text, word_dic):
"""
take a text and replace words that match a key in a dictionary with
the associated value, return the changed text
"""
rc = re.compile('|'.join(map(re.escape, word_dic)))
def translate(match):
return word_dic[match.group(0)]
return rc.sub(translate, text)
str1 = \
"""When we see a Space Shuttle sitting on its launch pad, there are two big
booster rockets attached to the sides of the main fuel tank. These are solid
rocket boosters, made by Thiokol at their factory in Utah. The engineers who
designed the solid rocket boosters might have preferred to make them a bit
fatter, but they had to be shipped by train from the factory to the launch
site. The railroad line from the factory runs through a tunnel in the
mountains. The boosters had to fit through that tunnel. The tunnel is
slightly wider than the railroad track. The width of the railroad track
came from the width of horse-drawn wagons in England, which were as wide
as two horses' behinds. So, a major design feature of what is the world's
most advanced transportation system was determined over two thousand years
ago by the width of a horse's ass!
"""
test_file = "Mword1.txt"
# create a test file for this example
fout = open(test_file, "w")
fout.write(str1)
fout.close()
# read the file
fin = open(test_file, "r")
str2 = fin.read()
fin.close()
# the dictionary has target_word:replacement_word pairs
word_dic = {
'booster': 'rooster',
'rocket': 'pocket',
'solid': 'salted',
'tunnel': 'funnel',
'ship': 'slip'}
# call the function and get the changed text
str3 = replace_words(str2, word_dic)
# test
print str3
# write changed text back out
fout = open("Mword2.txt", "w")
fout.write(str3)
fout.close()
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Thanks again, the last code example will work for me. I will have to read up on the module re to digest it all.
sneekula
Nearly a Posting Maven
2,427 posts since Oct 2006
Reputation Points: 961
Solved Threads: 212
Something like this (did not read the original code of this thread though, next time start your own thread and include link to old thread if you like)?
input_text = """this is a fat cat
that is a large pan
that is a thick slice of bread"""
targets, new, output = ['fat','thick'], 'thin', ''
for line in input_text.splitlines():
for target in targets:
if target in line:
output +="//Modification\n"
line = line.replace(target,new)
output += line+'\n'
print output
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852