【问题标题】:compare words in two lists in python比较python中两个列表中的单词
【发布时间】:2013-03-14 10:30:05
【问题描述】:

我希望有人在这个可能很简单的问题上提供帮助:我有一长串['word', 'another', 'word', 'and', 'yet', 'another'] 形式的单词。我想将这些单词与我指定的列表进行比较,从而查找目标单词是否包含在第一个列表中。

我想输出我的哪些“搜索”词包含在第一个列表中,以及它们出现了多少次。我尝试了类似list(set(a).intersection(set(b))) 的方法 - 但它会拆分单词并比较字母。

我如何写一个单词列表以与现有的长列表进行比较?以及如何输出共现及其频率?非常感谢您的时间和帮助。

【问题讨论】:

  • 你能贴一些你试过的代码吗? set(['word', 'another']) 计算结果为 set(['word', 'another']) 并且不会将单词拆分为字母。

标签: python list compare words


【解决方案1】:
>>> lst = ['word', 'another', 'word', 'and', 'yet', 'another']
>>> search = ['word', 'and', 'but']
>>> [(w, lst.count(w)) for w in set(lst) if w in search]
[('and', 1), ('word', 2)]

这段代码基本上遍历lst 的唯一元素,如果元素在search 列表中,它会将单词连同出现次数一起添加到结果列表中。

【讨论】:

    【解决方案2】:

    使用Counter 预处理您的单词列表:

    from collections import Counter
    a = ['word', 'another', 'word', 'and', 'yet', 'another']
    c = Counter(a)
    # c == Counter({'word': 2, 'another': 2, 'and': 1, 'yet': 1})
    

    现在您可以遍历新的单词列表并检查它们是否包含在此 Counter-dictionary 中,并且该值会为您提供它们在原始列表中的出现次数:

    words = ['word', 'no', 'another']
    
    for w in words:
        print w, c.get(w, 0)
    

    哪个打印:

    word 2
    no 0
    another 2
    

    或以列表形式输出:

    [(w, c.get(w, 0)) for w in words]
    # returns [('word', 2), ('no', 0), ('another', 2)]
    

    【讨论】:

    • 非常感谢。两种解决方案似乎都很好,但我的代码允许输入排序 [('S'), ('t'), ('o'), ('c'), ('k')] 当我输入库存在 sys.argv(2)。在执行程序时,如何将更多单词输入到可比较的列表中?并且使用您建议的两种解决方案,它会比较字母而不是整个单词 conll=open(sys.argv[1],'r') targetword=str(sys.argv[2]) vocab=[] c = Counter( vocab) print c for w in targetword: print w, c.get(w, 0) print [(w, vocab.count(w)) for w in set(vocab) if w in targetword] print targetword
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 2023-01-02
    相关资源
    最近更新 更多