1 回答
TA贡献1825条经验 获得超4个赞
因此,根据您提供的信息,我想当您看到另一个时,您想停止写作sold salt,然后从那里继续写作。这意味着在写入时,您只需要进行另一次检查(就像您已经做的那样),以确保要写入新文件的单词不是sold salt,如果是,则从那里中断。它看起来像这样:
for line in f_old:
line_words = line.split() # it is confusing changing the value of a variable within the
# loop, so I would recommend simply creating a new variable
if len(line_words) == 1:
# there was no need for a for loop here as we already know that there is only one element
f_result.write(line_words[0] + '\n')
else:
for word in range(len(line_words)-1): # as you will be accessing word+1 element,
# you need to look out for out of range indices
if line_words[word] == key_1 and line_words[word + 1] == key_2:
for i in range(len(line_words[word: word + 10]))):
if i != 0 and line_words[word+i] == key_1 and line_words[word+i+1] == key_2:
break
f_result.write(line_words[word+i] + ' ')
f_result.write('\n')
f_result.close()
我还建议使用枚举,然后仅使用索引来访问您需要的元素后面的元素,我认为它提供了更清晰的代码。
添加回答
举报