Python统计json每类文件标签数

​
import os
import json


# 获取包含JSON文件的目录列表
root_dir = 'C:/Users/xu\'xu/Desktop/prepare/dataset/JPEGImages'
json_files = [f for f in os.listdir(root_dir) if f.endswith('.json')]  # 获取文件名

# 统计每个类别出现的数量
categories_count = {}
for json_file in json_files:
    with open(os.path.join(root_dir, json_file), 'r') as f:
        data = json.load(f)
        for annotation in data['shapes']:
            category_name = annotation['label']
            # category_name = data['categories'][category_id]['name']
            # if category_name not in categories_count:
            #     categories_count[category_name] = 0

            if (category_name in categories_count.keys()):
                categories_count[category_name] += 1  # 如果标签不是第一次出现,则+1
            else:
                categories_count[category_name] = 1

# 输出结果
print("标签名称\t数量")
for category, count in categories_count.items():
    print(f"{category}\t{count}")

​

 代码中的json.load() 该函数需要一个打开的文件句柄作为输入,并返回Python对象

如上图所示,为了获取label对应的值就需要在多层嵌套中使用索引符[],递归地遍历对象并获取所有想要的数据

运行结果部分显示如下:

标签名称	数量
capillary	24
frayed edge	86
pit	61

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值