在Python中比较两个列表中的词

2 投票
2 回答
10470 浏览
提问于 2025-04-17 19:04

我希望有人能帮我解决一个可能很简单的问题:我有一长串单词,格式是 ['word', 'another', 'word', 'and', 'yet', 'another']。我想把这些单词和我指定的一个单词列表进行比较,看看目标单词是否在第一个列表中。

我想输出我“搜索”的单词在第一个列表中出现了多少次。我试过用 list(set(a).intersection(set(b))) 这样的方式,但它把单词拆开了,只比较字母。

我该如何写一个单词列表来和已有的长列表进行比较呢?我又该如何输出这些单词的出现次数和频率呢?非常感谢你的时间和帮助。

2 个回答

4

先用一个叫做 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 字典里,字典里的值会告诉你这些单词在原始列表中出现了多少次:

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)]
7
>>> 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 列表里,就把这个词和它出现的次数一起添加到结果列表中。

撰写回答