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

从多日气象文本文件提取指定日期数据及解决类型转换问题

解决气象数据提取时的float转换错误问题

直接按行列读取会碰到文件里的说明字符串,导致数值转换失败。核心思路是先过滤非数据行,精准定位目标日期的有效数据行,以下是具体实现方案(以Python为例):

实现步骤

  • 跳过空行、说明行,只处理符合格式的数据行
  • 匹配目标日期,验证数值列有效性后写入新文件

示例代码

# 配置参数
target_date = "2024-01-01"  # 要提取的目标日期
input_path = "weather_obs.txt"  # 原始数据文件路径
output_path = "target_day_weather.txt"  # 输出文件路径

with open(input_path, 'r', encoding='utf-8') as in_f, open(output_path, 'w', encoding='utf-8') as out_f:
    header_saved = False
    for line in in_f:
        line = line.strip()
        if not line:
            continue  # 跳过空行
        
        # 拆分行数据(根据实际文件分隔符调整,比如空格、制表符)
        row = line.split(',')
        # 跳过列数不足的说明行,假设数据行至少包含日期+3个数值列
        if len(row) < 4:
            # 若有表头,先写入输出文件
            if "日期" in line and not header_saved:
                out_f.write(line + '\n')
                header_saved = True
            continue
        
        # 匹配目标日期
        if row[0] == target_date:
            # 验证数值列是否合法,避免写入脏数据
            try:
                [float(col) for col in row[1:]]
                out_f.write(line + '\n')
            except ValueError:
                print(f"跳过格式错误行: {line}")

适配调整建议

  • 如果文件用制表符分隔,把split(',')改成split('\t')
  • 日期格式不同时(如2024/01/01),直接修改target_date为对应格式即可
  • 若说明行有固定标识(如以#开头),可以直接用if line.startswith('#')跳过

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:55:21