1.json文件数据
json文件数据长这样:
然后我们有多个json文件:
目标:
我们现在需要统计每个json文件所有label标签后的值的数量。
2.代码
import json
from os import listdir
path = "/content/data/" # .json文件目录
file_list = listdir(path) # 所有的.json文件
file_index = [] # 准备存放文件索引,为了按顺序读文件
for i in range(len(file_list)):
# 把文件名里的数字提出来排序
idx = file_list[i].split('.')[0].split("img")[1]
file_index.append(int(idx))
file_index = sorted(file_index)
total_label = [] # 统计所有文件的label标签数量
for file in file_index:
filename = path + 'img' + str(file) + '.json'
with open(filename, 'r') as f:
label_list = json.load(f)
# print(label_list)
t_dict = {} # 每个文件的label标签数量
for i, label_dict in enumerate(label_list['shapes']):
# print(label_dict['label'])
if label_dict['label'] not in t_dict:
t_dict[label_dict['label']] = 1
else:
t_dict[label_dict['label']] += 1
print(filename, "label统计:", t_dict)
total_label.append(t_dict)
# print(total_label)
# 统计所有文件的label标签数量,算是一个整合吧
temp = {}
for i, labels in enumerate(total_label):
# print(labels)
for j, label in enumerate(labels):
if label not in temp:
temp[label] = labels[label]
else:
temp[label] += labels[label]
print(temp)
最后结果如图: