如何用Counter统计多JSON文件嵌套字典中协议键的非空出现次数?
解决方法
直接遍历每个JSON文件,检查目标协议对应的列表是否非空,用Counter()直接累计计数即可——字典本身不可哈希,没法存入集合,完全没必要走那条弯路。
代码实现步骤
- 导入依赖模块
import json import os from collections import Counter
- 定义要统计的协议列表,初始化计数器
# 按需添加或修改要统计的协议 target_protocols = ['udp', 'tcp', 'icmp', 'http'] protocol_counter = Counter()
- 遍历所有JSON文件并统计
# 替换为你的JSON文件所在目录路径 json_dir = './your_json_files_dir' for file_name in os.listdir(json_dir): if not file_name.endswith('.json'): continue file_path = os.path.join(json_dir, file_name) with open(file_path, 'r', encoding='utf-8') as f: try: data = json.load(f) # 取出network字典,避免KeyError network_dict = data.get('network', {}) for proto in target_protocols: # 检查该协议对应的列表是否非空 if network_dict.get(proto, []): protocol_counter[proto] += 1 except json.JSONDecodeError: print(f"跳过无效JSON文件: {file_name}")
- 查看统计结果
print(protocol_counter) # 输出示例:Counter({'tcp': 156, 'udp': 123, 'icmp': 45, 'http': 89})
绘制直方图示例
如果需要可视化,用matplotlib直接基于Counter结果生成即可:
import matplotlib.pyplot as plt protocols = list(protocol_counter.keys()) counts = list(protocol_counter.values()) plt.bar(protocols, counts, color='#4287f5') plt.xlabel('网络协议') plt.ylabel('非空条目文件数量') plt.title('各协议在JSON文件中的出现次数') plt.tight_layout() plt.show()
关键说明
- 直接对每个文件的目标协议做非空判断,符合需求就给对应计数器加1,逻辑简单高效,完全避开集合的限制。
- 用
data.get('network', {})和network_dict.get(proto, [])可以避免文件结构不规范时抛出KeyError,增强代码鲁棒性。
内容的提问来源于stack exchange,提问作者jefazo92
相关产品推荐
相关产品推荐

