Guest User

Untitled

a guest
Jan 16th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. input_data = open('input.txt','r') #this opens the file to read it.
  2. output_data = open('output.txt','w') #this opens a file to write to.
  3.  
  4. userStr= (raw_input('Enter the word to be replaced:')) #this prompts the user for a word
  5. userReplace =(raw_input('What should I replace all occurences of ' + userStr + ' with?')) #this prompts the user for the replacement word
  6.  
  7.  
  8. for line in input_data:
  9. words = line.split()
  10. if userStr in words:
  11. output_data.write(line + userReplace)
  12. else:
  13. output_data.write(line)
  14.  
  15. print 'All occurences of '+userStr+' in input.txt have been replaced by '+userReplace+' in output.txt' #this tells the user that we have replaced the words they gave us
  16.  
  17.  
  18. input_data.close() #this closes the documents we opened before
  19. output_data.close()
  20.  
  21. if userStr in words:
  22. output_data.write(line + userReplace) # <-- Right here
  23. else:
  24. output_data.write(line)
  25.  
  26. for line in input_data:
  27. while userStr in line:
  28. index = line.index(userStr) # The place where `userStr` occurs in `line`.
  29.  
  30. # You need to cut `line` into two parts: the part before `index` and
  31. # the part after `index`. Remember to consider in the length of `userStr`.
  32.  
  33. line = part_before_index + userReplace + part_after_index
  34.  
  35. output_data.write(line + 'n') # You still need to add a newline
  36.  
  37. output_data.write(userReplace.join(line.split(userStr)))
Add Comment
Please, Sign In to add comment