【问题标题】:How do I find all unique words(no duplicates)?我如何找到所有唯一的单词(没有重复)?
【发布时间】:2015-07-05 09:08:17
【问题描述】:

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

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

【问题讨论】:

    标签: python list input store words


    【解决方案1】:

    这里有一个可能对你有帮助的 sn-p:

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

    【讨论】:

    • 效果很好。但是我如何只列出两个文件中都出现的单词呢?
    猜你喜欢
    • 2013-08-12
    • 2017-11-13
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 2010-12-22
    相关资源
    最近更新 更多