在特定文本文件中查找唯一单词,并显示在python文件中找到的所有唯一单词的列表

2024-09-28 05:25:52 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个程序,打开指定的文本文件,然后显示在该文件中找到的所有唯一单词的列表。

提示:将每个单词存储为集合的一个元素

def main():
    # Open the text file
    text_file = open('for_exercise4.txt', 'r')
    read_file = text_file.readline()

    uniquewords = set([])
    print list(uniquewords)

这就是我目前为止所开始的。 在这之后,我需要使用一个集合来显示文本文件中的唯一单词。在

编辑

我在练习中做了进一步的练习,这就是我想到的。在

^{pr2}$

编辑#2

def main():
    file = open("c://users/Brandon/Desktop/PythonClass/for_exercise4.txt", 'r')
    text = file.read()
    file.close()

    uniquewords = []
    word_list = text.split()

    for word in word_list:
        if word not in uniquewords:
            uniquewords.append(word)
            print(str(word))
    file.close()

main()

当我运行这个程序时,它会显示所有唯一的单词,但它不会将每个单词存储为一个集合的元素。在


Tags: text程序txt元素formaindefopen
1条回答
网友
1楼 · 发布于 2024-09-28 05:25:52

好吧,好吧,你需要意识到,在一个集合中,你不可能有相同的两个项目列出两次。这是他们的一个美丽之处。所以你真正需要做的就是这个。在

text_file = open(for_exercise4.txt, 'r')
read_file = text_file.read()
word_list = read_file.split()
uniquewords = set(word_list)

相关问题 更多 >

    热门问题