python - 计算列表元组中每个列表中给定单词的出现次数
问题描述
我有一个标记化句子的列表,我想计算几个单词的集体出现:例如:
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]
有任何想法吗?
解决方案
您可以在列表理解中使用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
如果足够大,请考虑使用集合。
推荐阅读
- excel - 如何验证返回“403”错误的 URL
- javascript - 如何在 Dreamweaver 上编辑倒数计时器
- tf.keras - 如何对 csv 中的一个热编码数据使用共享嵌入?
- ruby-on-rails - 通过 has_many 关系创建 has_one
- c++ - Assimp cmake 构建 Windows 大 .lib 文件
- firebase - 带有颤振共享待办事项列表的 Firestore 使用数组或集合
- python - 如何在 setup.py 文件中包含 conda 包依赖项?
- mariadb - MariaDB JSON_ARRAYAGG 给出错误的结果
- oop - 就我而言,是否可以实现具有不同算法语义的策略模式?
- facebook - 如果我使用商务套装,是否可以访问 Graph API 以检索真正的潜在客户?