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

動漫人物
TA貢獻1815條經(jīng)驗 獲得超10個贊
這是一個優(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)
添加回答
舉報
0/150
提交
取消