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()
我還建議使用枚舉,然后僅使用索引來訪問您需要的元素后面的元素,我認為它提供了更清晰的代碼。
添加回答
舉報