You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3解析多行JSON文件并统计符合scores≥8条件的字段出现次数

需求实现:统计符合条件的Name和Color出现次数

我们先明确场景:
你有一个多行JSON格式的data.txt文件,内容如下:

{"Name": "Brian","scores": 8, "color": "red"}
{"Name": "Lina","scores": 2, "color": "blue"}
{"Name": "Brian","scores": 10, "color": "black"}
{"Name": "Brian","scores": 9, "color": "black"}

原代码已经能过滤出scores≥8的数据,但现在需要统计这些符合条件的数据中Name字段和color字段的出现次数,期望得到结果:"Brian": 3 ,"black": 2 , "red": 1


方案1:使用collections.Counter(简洁高效)

Counter是Python标准库中专门用于统计元素出现次数的工具,代码会更简洁易读:

import json
from collections import Counter

# 初始化两个计数器,分别统计姓名和颜色
name_counter = Counter()
color_counter = Counter()

with open('data.txt') as f:
    for json_obj in f:
        student_dict = json.loads(json_obj)
        # 过滤scores≥8的数据
        if student_dict["scores"] >= 8:
            # 更新对应计数器
            name_counter[student_dict["Name"]] += 1
            color_counter[student_dict["color"]] += 1

# 合并两个计数器的结果,转换成目标格式
final_result = {**dict(name_counter), **dict(color_counter)}
print(final_result)

代码说明:

  • 导入Counter后,我们创建两个计数器对象分别处理姓名和颜色的统计。
  • 遍历文件每一行,解析JSON为字典后,判断分数是否符合要求,符合则更新计数器。
  • 最后合并两个计数器的字典结果,打印出来就是{'Brian': 3, 'black': 2, 'red': 1},和你期望的格式一致。

方案2:手动用字典统计(无需额外模块)

如果你不想导入collections模块,可以手动用字典来维护计数:

import json

# 初始化两个空字典,用于统计次数
name_count = {}
color_count = {}

with open('data.txt') as f:
    for json_obj in f:
        student_dict = json.loads(json_obj)
        if student_dict["scores"] >= 8:
            # 统计姓名出现次数
            current_name = student_dict["Name"]
            if current_name in name_count:
                name_count[current_name] += 1
            else:
                name_count[current_name] = 1
            
            # 统计颜色出现次数
            current_color = student_dict["color"]
            if current_color in color_count:
                color_count[current_color] += 1
            else:
                color_count[current_color] = 1

# 合并两个统计字典
final_result = {**name_count, **color_count}
print(final_result)

代码说明:

  • 用两个空字典分别记录姓名和颜色的出现次数。
  • 每次处理符合条件的数据时,判断对应的键是否已经在字典中:存在则计数+1,不存在则初始化为1。
  • 最后合并字典得到结果,效果和方案1完全一致。

内容的提问来源于stack exchange,提问作者Justin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 15:52:35