Python多CSV天气数据处理:需显示温湿度极值对应日期
解决方案
你的核心问题是未将温度、湿度数据与对应日期绑定,且日期格式需转换为英文月份+日期形式。以下是修改后的代码:
import os import csv from datetime import datetime class Weather: def main(self): path = r'C:\Users\someone\PycharmProjects\untitled\weatherfiles\\' os.system('cls') # 存储(温度数值, 原始日期字符串)的元组 temp_data = [] # 存储(湿度数值, 原始日期字符串)的元组 hum_data = [] for files in os.listdir(path): if files.endswith('.txt'): # 用os.path.join拼接路径更安全 with open(os.path.join(path, files), 'r') as weather: input_file = csv.reader(weather) for row in input_file: # 跳过数据不全的行 if len(row) < 8: continue date_str = row[0] date_parts = date_str.split('-') if len(date_parts) != 3 or date_parts[0] != '2013': continue # 校验温度数据有效性 temp_val = row[1].strip() if not (temp_val.isdigit() or (temp_val.startswith('-') and temp_val[1:].isdigit())): continue # 校验湿度数据有效性 hum_val = row[7].strip() if not hum_val.isdigit(): continue temp_data.append((int(temp_val), date_str)) hum_data.append((int(hum_val), date_str)) if not temp_data or not hum_data: print("未找到2013年的有效天气数据") return # 找出对应极值的条目 highest_temp = max(temp_data, key=lambda x: x[0]) lowest_temp = min(temp_data, key=lambda x: x[0]) highest_hum = max(hum_data, key=lambda x: x[0]) # 格式化日期为英文月份+日期 def format_date(date_str): date_obj = datetime.strptime(date_str, '%Y-%m-%d') return date_obj.strftime('%B %d') # 处理温度显示:正数小于10补前导零 def format_temp(temp): if temp >= 0 and temp < 10: return f"0{temp}" return str(temp) # 输出目标格式结果 print(f"Highest: {format_temp(highest_temp[0])}C on {format_date(highest_temp[1])}") print(f"Lowest: {format_temp(lowest_temp[0])}C on {format_date(lowest_temp[1])}") print(f"Humid: {highest_hum[0]}% on {format_date(highest_hum[1])}") # 启动程序 if __name__ == "__main__": weather_app = Weather() weather_app.main()
关键修改说明
- 数据绑定:改用元组存储数值与对应日期,确保每个数据都能关联到原始日期
- 数据校验:增加空行、无效数值的判断,避免因脏数据导致程序崩溃
- 日期转换:借助
datetime模块将YYYY-MM-DD格式转为英文月份+日期形式 - 数值格式化:对小于10的正数温度补前导零,匹配目标输出格式
- 效率优化:将数据收集与极值计算分离,避免循环内重复处理,提升运行效率
内容的提问来源于stack exchange,提问作者ciper-pol
相关产品推荐
相关产品推荐

