如何找到所有唯一的单词(没有重复的单词)?

2024-04-20 07:32:28 发布

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

我想找到所有的独特的话,在这两个文件。我能列出每个文件中的所有单词,但它给了我副本。我还想按字母顺序排列。我该怎么做呢?你知道吗

#!/usr/bin/python3

#First file
file = raw_input("Please enter the name of the first file: ")

store = open(file)

new = store.read()

#Second file
file2 = raw_input("Please enter the name of the second file: ")

store2 = open(file2)

new2 = store2.read()

for line in new.split():
    if line in new2:
            print line

Tags: 文件ofthestorenamenewreadinput
1条回答
网友
1楼 · 发布于 2024-04-20 07:32:28

以下是一个可能对您有所帮助的片段:

new = 'this is a bunch of words'
new2 = 'this is another bunch of words'

unique_words = set(new.split())
unique_words.update(new2.split())
sorted_unique_words = sorted(list(unique_words))
print('\n'.join(sorted_unique_words))

更新:

如果您只对两个文件共用的单词感兴趣,请执行以下操作:

unique_words = set(new.split())
unique_words2 = set(new2.split())
common_words = set.intersection(unique_words, unique_words2)
print('\n'.join(sorted(common_words)))

相关问题 更多 >