Replace words in a file

Thread Solved

Join Date: Oct 2006
Posts: 2,279
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 176
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Replace words in a file

 
0
  #1
Feb 19th, 2007
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?
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Apr 2006
Posts: 148
Reputation: ghostdog74 is on a distinguished road 
Solved Threads: 40
ghostdog74 ghostdog74 is offline Offline
Junior Poster

Re: Replace words in a file

 
0
  #2
Feb 19th, 2007
Originally Posted by sneekula View Post
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
  1. o = open("output","a") #open for append
  2. for line in open("file"):
  3. line = line.replace("someword","newword")
  4. o.write(line + "\n")
  5. o.close()

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

3) using regular expression and reading the whole file into memory
  1. import re
  2. o = open("output","w")
  3. data = open("file").read()
  4. o.write( re.sub("someword","newword",data) )
  5. 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
  1. import fileinput
  2. for line in fileinput.FileInput("file",inplace=1):
  3. line = line.replace("blah","blahblah")
  4. print line
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,279
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 176
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Replace words in a file

 
0
  #3
Feb 20th, 2007
Thanks ghostdog!
I will have to play with those code ideas. I need to replace several different words in the text file.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,022
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 932
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Replace words in a file

 
0
  #4
Feb 21st, 2007
Here is an example, where the target and replacement words are in a dictionary. The Python module re is used to do the gruntwork ...
  1. # read a text file, replace multiple words specified in a dictionary
  2. # write the modified text back to a file
  3.  
  4. import re
  5.  
  6. def replace_words(text, word_dic):
  7. """
  8. take a text and replace words that match a key in a dictionary with
  9. the associated value, return the changed text
  10. """
  11. rc = re.compile('|'.join(map(re.escape, word_dic)))
  12. def translate(match):
  13. return word_dic[match.group(0)]
  14. return rc.sub(translate, text)
  15.  
  16.  
  17. str1 = \
  18. """When we see a Space Shuttle sitting on its launch pad, there are two big
  19. booster rockets attached to the sides of the main fuel tank. These are solid
  20. rocket boosters, made by Thiokol at their factory in Utah. The engineers who
  21. designed the solid rocket boosters might have preferred to make them a bit
  22. fatter, but they had to be shipped by train from the factory to the launch
  23. site. The railroad line from the factory runs through a tunnel in the
  24. mountains. The boosters had to fit through that tunnel. The tunnel is
  25. slightly wider than the railroad track. The width of the railroad track
  26. came from the width of horse-drawn wagons in England, which were as wide
  27. as two horses' behinds. So, a major design feature of what is the world's
  28. most advanced transportation system was determined over two thousand years
  29. ago by the width of a horse's ass!
  30. """
  31.  
  32. test_file = "Mword1.txt"
  33. # create a test file for this example
  34. fout = open(test_file, "w")
  35. fout.write(str1)
  36. fout.close()
  37.  
  38. # read the file
  39. fin = open(test_file, "r")
  40. str2 = fin.read()
  41. fin.close()
  42.  
  43. # the dictionary has target_word:replacement_word pairs
  44. word_dic = {
  45. 'booster': 'rooster',
  46. 'rocket': 'pocket',
  47. 'solid': 'salted',
  48. 'tunnel': 'funnel',
  49. 'ship': 'slip'}
  50.  
  51. # call the function and get the changed text
  52. str3 = replace_words(str2, word_dic)
  53.  
  54. # test
  55. print str3
  56.  
  57. # write changed text back out
  58. fout = open("Mword2.txt", "w")
  59. fout.write(str3)
  60. fout.close()
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,279
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 176
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Replace words in a file

 
0
  #5
Feb 21st, 2007
Thanks again, the last code example will work for me. I will have to read up on the module re to digest it all.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 5
Reputation: Shraddha Kiran is an unknown quantity at this point 
Solved Threads: 0
Shraddha Kiran Shraddha Kiran is offline Offline
Newbie Poster

Re: Replace words in a file

 
0
  #6
Jun 24th, 2009
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??
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC