gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:11:30 25 4
gpt4 key购买 nike

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

example_list = (['hey', 'there', 'you', 'how', 'are', 'you'],
['i', 'am', 'fine', 'how', 'about', you],
['i', 'am', 'good'])
现在我想计算以下单词在每个列表中出现的次数并将分数 append 到列表中
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]
有任何想法吗?

最佳答案

您可以使用 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,请考虑使用集合足够大。

关于python - 计算列表元组中每个列表中给定单词的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64683034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com