编写一个程序,打开指定的文本文件,然后显示在该文件中找到的所有唯一单词的列表。
提示:将每个单词存储为集合的一个元素
def main():
# Open the text file
text_file = open('for_exercise4.txt', 'r')
read_file = text_file.readline()
uniquewords = set([])
print list(uniquewords)
这就是我目前为止所开始的。 在这之后,我需要使用一个集合来显示文本文件中的唯一单词。在
我在练习中做了进一步的练习,这就是我想到的。在
^{pr2}$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()
当我运行这个程序时,它会显示所有唯一的单词,但它不会将每个单词存储为一个集合的元素。在
好吧,好吧,你需要意识到,在一个集合中,你不可能有相同的两个项目列出两次。这是他们的一个美丽之处。所以你真正需要做的就是这个。在
相关问题 更多 >
编程相关推荐