繁体   English   中英

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

[英]How do I find all unique words(no duplicates)?

我想找到两个文件中所有的唯一词。 我能够列出每个文件中的所有单词,但是它给了我重复的单词。 我也想按字母顺序对它们进行排序。 我该怎么做呢?

#!/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

这是一个片段,可能会帮助您:

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)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM