Replace without the replace function

Posted by Molly Potter on Stack Overflow See other posts from Stack Overflow or by Molly Potter
Published on 2012-10-02T03:22:15Z Indexed on 2012/10/02 3:37 UTC
Read the original article Hit count: 232

Filed under:

Assignment: Let X and Y be two words. Find/Replace is a common word processing operation that finds each occurrence of word X and replaces it with word Y in a given document.

Your task is to write a program that performs the Find/Replace operation. Your program will prompt the user for the word to be replaced (X), then the substitute word (Y ). Assume that the input document is named input.txt. You must write the result of this Find/Replace operation to a file named output.txt. Lastly, you cannot use the replace() string function built into Python (it would make the assignment much too easy).

To test your code, you should modify input.txt using a text editor such as Notepad or IDLE to contain different lines of text. Again, the output of your code must look exactly like the sample output.

This is my code:

 input_data = open('input.txt','r') #this opens the file to read it. 
 output_data = open('output.txt','w') #this opens a file to write to. 

 userStr= (raw_input('Enter the word to be replaced:')) #this prompts the user for a word 
 userReplace =(raw_input('What should I replace all occurences of ' + userStr + ' with?')) #this      prompts the user for the replacement word


 for line in input_data:
    words = line.split()
    if userStr in words:
       output_data.write(line + userReplace)
    else:
       output_data.write(line)

 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


 input_data.close() #this closes the documents we opened before 
 output_data.close()

It won't replace anything in the output file. Help!

© Stack Overflow or respective owner

Related posts about python