首页 > 解决方案 > 在 IDF 的字典列表中计数

问题描述

我有一个表格的字典列表

list_of_dicts = [{id1: [word1, word2, word3...]}, 
{id1: [word1, word2, word3..]},..]

我想计算一个单词在整个列表中出现的次数,而不仅仅是一个值列表。我很困惑我应该使用哪种 for 循环结构。

我试过这个:

from collections import Counter
count = Counter()
term = ""
for dict in list_of_dicts:
  for key, val in dict.items():
    for word in val:
      term = word
  counter = count[term]
  term = ""
  print(counter)

这给了我零。

非常感谢任何提示如何进行!

编辑:我想用它的计数替换有问题的单词,所以对于上面的例子,这将是:list_of_dicts = [{id1: [2, 2, 2...]}, {id1: [2, 2, 2..]},..]

标签: pythondictionarycounttf-idf

解决方案


我假设列表只包含字典对象,每个字典都可以有一个单词列表。

我不确定,您counter = count(term)通过设置来实现什么,并在此之上实现search_term。那里似乎缺少了什么。

无论如何,我已经尝试过了,并且它有效。

list_of_dicts = [{'id1':['ayush', 'mishra', 'lol']}, {'id2':['ayush', 'mishra2', 'lol']}, {'id3':['ayush2', 'mishra3', 'lol']}]
cnt = 0
target_term = "mishra"
for dict in list_of_dicts:
  for key, val in dict.items():
    for word in val:
      if word == target_term:
        cnt+=1
print(cnt)

推荐阅读