我的代碼能夠顯示文本文件中以特定字母開頭的每個(gè)單詞,但我希望它不顯示重復(fù)的單詞。這是我的代碼:with open('text.txt','r') as myFile: data=myFile.read().lower()for s in data.split(): if s.startswith("r"): print(s)就像我說的,我的代碼確實(shí)打印了單詞,但它顯示了重復(fù)項(xiàng)。感謝您的幫助
2 回答

動(dòng)漫人物
TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
這是一個(gè)優(yōu)化版本,它將逐行讀取文件而不將其全部加載到內(nèi)存中:
seen_words = set()
with open('text.txt', 'r') as my_file:
for line in my_file:
for word in line.lower().split():
if word not in seen_words:
print(word)
seen_words.add(word)
添加回答
舉報(bào)
0/150
提交
取消