【问题标题】:Count Occurence in Json Array within objects计数对象内 Json 数组中的出现次数
【发布时间】:2020-05-23 12:20:07
【问题描述】:

我有下面的 json,我试图从中计算 Python 中 Latin America 等标签的出现次数。由于它出现了两次,它应该为“Latin America”返回 2,为“Mexico”、“Health”和“Costa Rica”返回 1。

{
"AlJazeera_data": [
 {
  "name": "Mexico City hospitals reaching breaking point",
  "url": "https://www.aljazeera.com/news/",
  "tags": [
     "Latin America",
     "Mexico",
     "Health"
      ],
   "author": "Manuel Rapalo"
},
{
   "name": "Football matches resume in Costa Rica as virus curbs ease",
   "url": "https://www.aljazeera.coml",
   "tags": [
      "Latin America",
      "Costa Rica"
      ],
    "author": "Manuel Rapalo"
}]
}

使用此代码:

import json
from collections import Counter

with open('../../Resources/Aljazeera.json') as f:
   data = json.load(f)

for item in data['AlJazeera_data']:
    for t in item['tags']:
        print(t)

我得到了所有标签列表的输出,但我一直在计算所有标签的计数。

【问题讨论】:

  • 如果你有这些物品,为什么不把它们放在一个清单上,或者更好collections.Counter

标签: python json count find-occurrences


【解决方案1】:

你可以做类似的事情

import json
from collections import Counter

with open('../../Resources/Aljazeera.json') as f:
   data = json.load(f)

all_tags = Counter()

for item in data['AlJazeera_data']:
    all_tags.update(item['tags']):

print(all_tags)

编辑:正如另一张海报指出的那样,不需要第二次调用 Counter

【讨论】:

  • 非常感谢您的指导,这对我帮助很大。
  • 取决于您要计算的百分比 - 如果它是所有标签的简单百分比,您可以通过 sum(all_tags.values()) 找到总数,然后您可以使用它来查找百分比
【解决方案2】:

你需要用每个标签列表.update()计数器

tags = Counter()
for item in data['AlJazeera_data']:
    tags.update(item['tags'])

print(tags) # Counter({'Latin America': 2, 'Mexico': 1, 'Health': 1, 'Costa Rica': 1})
print(tags.most_common(1)) # [('Latin America', 2)]

total = sum(tags.values())
print(total) # 5

tags_percentage = {k: v/total for k,v in tags.items()}
print(tags_percentage) # {'Latin America': 0.4, 'Mexico': 0.2, 'Health': 0.2, 'Costa Rica': 0.2}

【讨论】:

  • 哦,我的错...只是我的一个简单错误...非常感谢您的指导
  • @EhteshamAbad 做 3 个“?”让问题比一个问题更重要?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 1970-01-01
相关资源
最近更新 更多