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
相关产品推荐
相关产品推荐

