DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Python (http://www.daniweb.com/forums/forum114.html)
-   -   Replace words in a file (http://www.daniweb.com/forums/thread70426.html)

sneekula Feb 19th, 2007 1:50 pm
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?

ghostdog74 Feb 19th, 2007 10:39 pm
Re: Replace words in a file
 
Quote:

Originally Posted by sneekula (Post 317313)
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?

there are several ways.
1) reading with for loop
o = open("output","a") #open for append
for line in open("file"):
  line = line.replace("someword","newword")
  o.write(line + "\n")
o.close()

2) with while loop
f = open("file")
o = open("output","a")
while 1:
  line = f.readline()
  if not line: break
  line = line.replace("someword","newword")
  o.write(line + "\n")
o.close()

3) using regular expression and reading the whole file into memory
import re
o = open("output","w")
data = open("file").read()
o.write( re.sub("someword","newword",data)  )
o.close()

If you don't want to explicitly declare file handles for writing to output file, you can use fileinput module, to modify file in place
import fileinput
for line in fileinput.FileInput("file",inplace=1):
  line = line.replace("blah","blahblah")
  print line

sneekula Feb 20th, 2007 3:21 pm
Re: Replace words in a file
 
Thanks ghostdog!
I will have to play with those code ideas. I need to replace several different words in the text file.

vegaseat Feb 21st, 2007 3:50 am
Re: Replace words in a file
 
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()

sneekula Feb 21st, 2007 3:30 pm
Re: Replace words in a file
 
Thanks again, the last code example will work for me. I will have to read up on the module re to digest it all.

Shraddha Kiran Jun 24th, 2009 9:52 am
Re: Replace words in a file
 
If i wanted to read the words to be replaced from another text file and then replace them wat modifications to the code would i have to make??


All times are GMT -4. The time now is 8:59 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC