在对象内的Json数组中计数出现次数。

问题描述 投票:0回答:1

我有下面的json,我想统计一下标签的出现次数,如 拉美 在Python中,由于它出现了两次,所以它应该返回2个 "拉丁美洲 "和1个 "墨西哥"、"健康 "和 "哥斯达黎加"。中出现了两次,它应该返回2个 "拉丁美洲",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)

我得到了所有标签列表的输出结果 但我在计算所有标签的数量时卡住了。

python count find-occurrences
1个回答
0
投票

你可以做一些像

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是不需要的。


0
投票

你需要 .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}
© www.soinside.com 2019 - 2024. All rights reserved.