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

Python 3从JSON数据库提取数据:统计气温冰点上下次数遇阻

解决JSON数据加载与气温统计问题

Hey Samantha, let's break this down and get your program working smoothly. Your plan is solid—let's translate those steps into actionable code and address potential pitfalls that might be blocking you.

1. 编写JSON数据加载函数

首先,我们用Python内置的json模块来加载文件。这个函数会加入基础异常处理,帮你排查加载失败的常见问题(比如文件找不到、JSON格式错误):

import json

def load_json_data(file_path):
    try:
        with open(file_path, 'r') as f:
            data = json.load(f)
        # 确认加载的数据是字典列表;如果JSON外层有包裹键(比如"data"),可根据实际结构调整
        if not isinstance(data, list):
            data = data.get("records", [])  # 替换成你JSON中实际的列表键名
        return data
    except FileNotFoundError:
        print(f"错误:找不到文件 {file_path}")
        return []
    except json.JSONDecodeError:
        print("错误:JSON文件格式不正确")
        return []

2. 提取平均气温信息

接下来,从每个字典中提取平均气温。这里要注意两个关键细节:

  • 必须匹配JSON中气温字段的准确键名(比如"avg_temp"、"average_temperature",大小写、符号完全一致)
  • 若气温值是字符串格式,要先转换为数值类型(float或int)
def extract_avg_temperatures(data):
    temperatures = []
    for entry in data:
        # 替换成你JSON中实际的气温键名
        temp_value = entry.get("average_temperature")
        if temp_value is not None:
            try:
                temp = float(temp_value)
                temperatures.append(temp)
            except ValueError:
                print(f"警告:无法转换气温值 '{temp_value}' 为数值,已跳过该条目")
        else:
            print("警告:条目缺失平均气温字段,已跳过")
    return temperatures

3. 统计气温高于/低于冰点的次数

最后,遍历提取的气温列表,统计大于0℃和小于0℃的次数(可选统计刚好等于0℃的情况):

def count_temperature_categories(temperatures):
    above_freezing = 0
    below_freezing = 0
    at_freezing = 0  # 可选:统计刚好0℃的情况

    for temp in temperatures:
        if temp > 0:
            above_freezing += 1
        elif temp < 0:
            below_freezing += 1
        else:
            at_freezing += 1

    return {
        "高于冰点次数": above_freezing,
        "低于冰点次数": below_freezing,
        "等于冰点次数": at_freezing
    }

整合并测试整个流程

把所有函数串起来,替换成你的JSON文件路径即可测试:

if __name__ == "__main__":
    json_file = "weather_database.json"  # 替换成你的JSON文件路径
    weather_data = load_json_data(json_file)
    
    if weather_data:
        temps = extract_avg_temperatures(weather_data)
        if temps:
            stats = count_temperature_categories(temps)
            print("气温统计结果:")
            print(f"平均气温高于冰点(>0℃)的次数:{stats['高于冰点次数']}")
            print(f"平均气温低于冰点(<0℃)的次数:{stats['低于冰点次数']}")
            print(f"平均气温等于冰点(=0℃)的次数:{stats['等于冰点次数']}")
        else:
            print("没有提取到有效的气温数据")
    else:
        print("无法加载JSON数据")

常见问题排查

如果还是无法提取信息,大概率是以下原因:

  • JSON结构不匹配:你的JSON可能不是直接的字典列表,而是嵌套在某个键下(比如{"data": [...]}),需要在load_json_data函数中调整提取逻辑
  • 键名拼写错误:确认你用的键名和JSON中的完全一致(比如别把"average_temp"写成"avg_temperature")
  • 气温数据带单位:如果气温是"5°C"这种格式,需要先去掉单位再转换数值(比如temp_value.strip("°C"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:50:06