计算列表元组中每个列表给定单词的出现次数

Count occurrences of given words per each list in a tuple of lists

我有一个标记化句子列表,我想统计几个单词的出现次数: 例如:

example_list = (['hey', 'there', 'you', 'how', 'are', 'you'],
                ['i', 'am', 'fine', 'how', 'about', you],
                ['i', 'am', 'good'])

现在我想计算以下单词在每个列表中出现的次数,并将分数附加到列表中

score = []
test = ['hey', 'you']

我试试下面的代码:

for i in range(len(test)):
   for j in range(len(example_list)):
       score1.append(example_list[j].count(test[i]))

并得到输出:

[1, 0, 0, 2, 1, 0]

而我想要输出:

[3, 1, 0]

有什么想法吗?

只需使用传统的 for 循环:

example_list = (['hey', 'there', 'you', 'how', 'are', 'you'],
                ['i', 'am', 'fine', 'how', 'about', 'you'],
                ['i', 'am', 'good'])
test = ['hey', 'you']
score = []

for lst in example_list:
    total = 0
    for word in test:
        total += lst.count(word)
    score.append(total)

print(score)

输出:

[3, 1, 0]

您可以使用带有 sum 的嵌套列表理解来添加 test 中所有元素的出现次数。

此外,您可能希望从 test 构建一个 set 以加快查找速度:

test = set(['hey', 'you'])

[sum(s in test for s in l) for l in example_list]
# [3, 1, 0]

您可以在列表理解中使用 sum

example_list = (['hey', 'there', 'you', 'how', 'are', 'you'],
                ['i', 'am', 'fine', 'how', 'about', 'you'],
                ['i', 'am', 'good'])



test = ['hey', 'you']


score = [sum(s in test for s in lst) for lst in example_list]
print(score)

输出

[3, 1, 0]

如果 test 足够大,可以考虑使用集合。

您可以使用 Counter 完成此任务:

from collections import Counter


counters = [Counter(l) for l in example_list]
occurrences = [sum([c[word] for word in test if word in c]) for c in counters]

print(occurrences) # [3, 1, 0]