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

Python或Linux下按条件修改txt文件 合并同轨道号数据取起止时间

问题答复

这个需求完全可以实现,实现成本很低,以下是相关说明:

可用工具/模块

  • 命令行方案:无需额外安装软件,直接使用Linux/Unix系统自带的awk、sort即可完成
  • Python方案:仅依赖Python标准库,不需要安装任何第三方模块,逻辑可定制性更强

核心实现思路

只需要按「轨道号分组」,每组内做聚合计算即可,具体逻辑如下:

  1. 读取txt文件的每一行,按空格拆分得到各个字段,注意处理行末尾多余的空格
  2. 用字典存储分组结果,key为轨道号,value存储该轨道对应的年、月、日、最小起始时间(第4、5列的时分组合)、最大结束时间(第6、7列的时分组合)
  3. 遍历每一条记录时:
    • 如果轨道号不在字典中,就把当前记录的年、月、日、起始时分、结束时分存入字典
    • 如果轨道号已存在,就比较当前记录的起始时分和已存储的最小起始时分,取更小的那个;比较当前记录的结束时分和已存储的最大结束时分,取更大的那个
  4. 遍历完成后,把字典里的所有值按要求的格式输出即可

注意:上述实现默认同一轨道号的所有记录都属于同一天,和需求描述一致。如果存在轨道号跨天的场景,需要调整逻辑加入日期的判断。

参考实现(Python)

orbit_dict = {}
# 读取输入文件
with open("input.txt", "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        parts = list(map(int, line.split()))
        year, month, day, start_h, start_m, end_h, end_m, orbit = parts
        # 时分转成整数方便比较,比如11点17分转为1117
        start_val = start_h * 100 + start_m
        end_val = end_h * 100 + end_m
        if orbit not in orbit_dict:
            orbit_dict[orbit] = [year, month, day, start_h, start_m, end_h, end_m]
        else:
            # 更新最早起始时间
            exist_start = orbit_dict[orbit][3] * 100 + orbit_dict[orbit][4]
            if start_val < exist_start:
                orbit_dict[orbit][3] = start_h
                orbit_dict[orbit][4] = start_m
            # 更新最晚结束时间
            exist_end = orbit_dict[orbit][5] * 100 + orbit_dict[orbit][6]
            if end_val > exist_end:
                orbit_dict[orbit][5] = end_h
                orbit_dict[orbit][6] = end_m
# 输出结果
with open("output.txt", "w", encoding="utf-8") as f:
    for orbit, vals in orbit_dict.items():
        out_line = f"{vals[0]} {vals[1]} {vals[2]} {vals[3]} {vals[4]} {vals[5]} {vals[6]} {orbit}\n"
        f.write(out_line)
        print(out_line.strip())

参考实现(awk一行命令)

如果习惯用命令行操作,直接在终端执行以下命令即可得到结果:

awk '{
    orbit = $8;
    start = $4*100 + $5;
    end = $6*100 + $7;
    if (!(orbit in dict)) {
        dict[orbit] = $1" "$2" "$3" "$4" "$5" "$6" "$7;
        min_start[orbit] = start;
        max_end[orbit] = end;
    } else {
        if (start < min_start[orbit]) {
            split(dict[orbit], arr, " ");
            dict[orbit] = arr[1]" "arr[2]" "arr[3]" "$4" "$5" "arr[6]" "arr[7];
            min_start[orbit] = start;
        }
        if (end > max_end[orbit]) {
            split(dict[orbit], arr, " ");
            dict[orbit] = arr[1]" "arr[2]" "arr[3]" "arr[4]" "arr[5]" "$6" "$7;
            max_end[orbit] = end;
        }
    }
} END {
    for (o in dict) print dict[o], o
}' input.txt | sort -k8n

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:36:05