作业:设X和Y为两个单词。查找/替换是一种常见的字处理操作,它可以查找每个字X的出现,并用给定文档中的字Y替换它。替换不带替换功能
你的任务是编写一个执行查找/替换操作的程序。您的程序将提示用户输入要替换的单词(X),然后替换单词(Y)。假设输入文档名为input.txt。您必须将此查找/替换操作的结果写入名为output.txt的文件。最后,你不能使用Python中内置的replace()字符串函数(这会使分配变得非常容易)。
要测试您的代码,您应该使用文本编辑器(如记事本或IDLE)修改input.txt以包含不同的文本行。同样,代码的输出必须与样例输出完全相同。
这是我的代码:
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()
它不会取代在输出文件中任何事情。帮帮我!
你需要找到这个词在该行出现,然后换行的一部分。 –
你应该尝试自己解决这个问题。这是一项家庭作业。如果你在这里得到你的答案,你将不会学习如何自己做...加油!这是一个不错的功课!当我在学校时,我希望我有这样的作业...... – marianobianchi
你似乎没有使用'replace'函数... – nneonneo