Python 不带Replace功能的Replace
作业:设X和Y为两个单词。查找/替换是一种常见的字处理操作,它查找给定文档中出现的每个单词X,并将其替换为单词Y 您的任务是编写一个执行查找/替换操作的程序。您的程序将提示用户输入要替换的单词(X),然后输入替换单词(Y)。假设输入文档名为input.txt。必须将此查找/替换操作的结果写入名为output.txt的文件。最后,您不能使用Python中内置的replace()字符串函数(这会使赋值过于简单) 要测试代码,应使用文本编辑器(如记事本或IDLE)修改input.txt,以包含不同的文本行。同样,代码的输出必须与示例输出完全相同 这是我的代码:Python 不带Replace功能的Replace,python,Python,作业:设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()
它不会替换输出文件中的任何内容。救命啊 问题在于,如果找到匹配项,代码只会将替换字符串粘贴到行的末尾:
if userStr in words:
output_data.write(line + userReplace) # <-- Right here
else:
output_data.write(line)
解决
replace
问题的一个稍微令人恼火的方法是使用re.sub()
您可以使用split
和join
来实现replace
output_data.write(userReplace.join(line.split(userStr)))
你需要找出单词在这一行中出现的位置,然后改变这一部分。你应该试着自己解决这个问题。这是家庭作业。如果你在这里得到你的答案,你将无法学会如何自己去做。。。来吧这是一个很好的家庭作业!我希望我在学校的时候有这样的家庭作业……你似乎根本没有使用
replace
功能。。。
output_data.write(userReplace.join(line.split(userStr)))