我的代码能够显示文本文件中以特定字母开头的每个单词,但我希望它不显示重复的单词。这是我的代码: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条经验 获得超10个赞
这是一个优化版本,它将逐行读取文件而不将其全部加载到内存中:
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
提交
取消