2012-10-02 85 views
-1

作业:设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() 

它不会取代在输出文件中任何事情。帮帮我!

+0

你需要找到这个词在该行出现,然后换行的一部分。 –

+0

你应该尝试自己解决这个问题。这是一项家庭作业。如果你在这里得到你的答案,你将不会学习如何自己做...加油!这是一个不错的功课!当我在学校时,我希望我有这样的作业...... – marianobianchi

+0

你似乎没有使用'replace'函数... – nneonneo

回答

2

的问题是,如果找到匹配,你的代码只是坚持替换字符串到行的末尾:

if userStr in words: 
    output_data.write(line + userReplace) # <-- Right here 
else: 
    output_data.write(line) 

既然你不能使用.replace(),你将不得不解决它。我会找到你的文字出现在哪里,将这部分剪掉,然后将userReplace放在原处。

要做到这一点,尝试这样的事情:

for line in input_data: 
    while userStr in line: 
     index = line.index(userStr) # The place where `userStr` occurs in `line`. 

     # You need to cut `line` into two parts: the part before `index` and 
     # the part after `index`. Remember to consider in the length of `userStr`. 

     line = part_before_index + userReplace + part_after_index 

    output_data.write(line + '\n') # You still need to add a newline 

稍微更恼人的方式来解决replace是使用re.sub()

1

你可以只使用splitjoin实施replace

output_data.write(userReplace.join(line.split(userStr)))