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

Python 2.7.5处理input.txt:提取指定列并跳过特定行求助

解决方案代码
import re
import csv

# 定义需要跳过的标签编号
SKIP_TAGS = {'00033', '00272'}
# 匹配[XXXYY] {TAG}格式行的正则
tag_pattern = re.compile(r'^\[(\d{5})\] (\w+)$')

def process_input(input_path, output_path):
    skip_mode = False
    with open(input_path, 'r') as infile, open(output_path, 'w') as outfile:
        writer = csv.writer(outfile)
        # 写入表头(可根据预期输出调整)
        writer.writerow(['Col1', 'Col2', 'Col3_Prefix'])
        
        for line in infile:
            line = line.strip()
            if not line:
                continue  # 跳过空行
            
            # 匹配标签行
            tag_match = tag_pattern.match(line)
            if tag_match:
                tag_id = tag_match.group(1)
                # 开启/关闭跳过模式
                skip_mode = tag_id in SKIP_TAGS
                continue
            
            # 跳过模式下直接忽略行
            if skip_mode:
                continue
            
            # 处理以J开头的行
            if line.startswith('J'):
                columns = line.split()
                if len(columns) >= 3:
                    col1 = columns[0]
                    col2 = columns[1]
                    col3_prefix = columns[2][:3]
                    writer.writerow([col1, col2, col3_prefix])

if __name__ == '__main__':
    process_input('input.txt', 'output.csv')
关键说明
  • 正则匹配:tag_pattern精准捕捉[5位数字] 标签名格式的行,提取标签编号用于判断是否跳过;以J开头的行直接用startswith判断,比正则更高效
  • 跳过逻辑:用skip_mode布尔变量控制状态,遇到指定标签行时开启跳过,直到下一个标签行重置状态
  • 列提取:用split()自动处理任意空白分隔的列(多空格、制表符都兼容),第三列仅保留前3个字符
  • Python 2.7兼容:所有写法完全适配2.7.5版本,仅使用允许的re和csv库,无额外依赖
调整建议
  • 若输入文件列分隔符是固定制表符,可将split()改为split('\t')
  • 若需要将标签信息也写入输出,可在匹配到标签行时记录当前标签,写入J行数据时一并加入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:05:20