显示文件中以特定字母开头的单词

我的代码能够显示文本文件中以特定字母开头的每个单词,但我希望它不显示重复的单词。这是我的代码:


with open('text.txt','r') as myFile:

    data=myFile.read().lower()


for s in data.split():

    if s.startswith("r"):

        print(s)

就像我说的,我的代码确实打印了单词,但它显示了重复项。感谢您的帮助


森林海
浏览 169回答 2
2回答

动漫人物

这是一个优化版本,它将逐行读取文件而不将其全部加载到内存中: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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python