1 回答

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
因此,根據(jù)您提供的信息,我想當(dāng)您看到另一個(gè)時(shí),您想停止寫(xiě)作sold salt,然后從那里繼續(xù)寫(xiě)作。這意味著在寫(xiě)入時(shí),您只需要進(jìn)行另一次檢查(就像您已經(jīng)做的那樣),以確保要寫(xiě)入新文件的單詞不是sold salt,如果是,則從那里中斷。它看起來(lái)像這樣:
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()
我還建議使用枚舉,然后僅使用索引來(lái)訪問(wèn)您需要的元素后面的元素,我認(rèn)為它提供了更清晰的代碼。
添加回答
舉報(bào)