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

如何将含Position的行转为新列(Python/Unix Shell实现)

文本行重排为制表符分隔格式解决方案

Unix Shell 实现

使用 awk 命令可高效处理这类上下文关联的文本转换需求:

awk '/^Position/ {pos=$0; next} {print $0 "\t" pos}' input.txt
  • 逻辑说明:
    • 匹配以 Position 开头的行时,将该行内容存入变量 pos,并跳过当前行后续处理
    • 非 Position 行(各类 Val 行),直接输出当前行内容 + 制表符 + 已记录的 pos 值

Python 实现

逐行读取处理(适合大文件)

逐行读取文件,避免一次性加载全部内容到内存:

current_pos = ""
with open("input.txt", "r") as f:
    for line in f:
        line = line.strip()
        if not line:
            continue  # 跳过空行
        if line.startswith("Position"):
            current_pos = line
        else:
            print(f"{line}\t{current_pos}")

全量读取处理(适合小文件)

一次性读取所有行后再处理,代码更简洁:

with open("input.txt", "r") as f:
    # 过滤空行并去除每行首尾空白
    lines = [line.strip() for line in f if line.strip()]

current_pos = ""
for line in lines:
    if line.startswith("Position"):
        current_pos = line
    else:
        print(f"{line}\t{current_pos}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:30:59