如何用Python匹配两个输入文件内容并生成指定格式输出?
解决方案
核心思路
- 先解析
input1.txt,把每个hstep3_*左值和对应的值存入字典,方便后续快速匹配 - 遍历
input2.txt,筛选出match hstep*格式的行,提取左值和括号内的内容 - 用左值去字典中查找对应的值,按指定格式写入
output.txt
Python 实现代码
import re # 解析input1.txt,构建左值到值的映射 hstep_map = {} with open('input1.txt', 'r') as f1: for line in f1: line = line.strip() if not line: continue # 匹配input1的行格式:hstep3_num00 = a5; match = re.match(r'^(hstep3_\w+)\s*=\s*(\w+);$', line) if match: key = match.group(1) value = match.group(2) hstep_map[key] = value # 解析input2.txt,匹配对应内容并生成输出 with open('input2.txt', 'r') as f2, open('output.txt', 'w') as out_f: for line in f2: line = line.strip() if not line: continue # 匹配input2的match行格式:match hstep3_num00 = {u_ku,b,ntv,q}; match = re.match(r'^match\s+(hstep3_\w+)\s*=\s*({[^}]+});$', line) if match: key = match.group(1) bracket_content = match.group(2) # 检查是否在input1中有对应记录 if key in hstep_map: # 按指定格式输出,空格数量可按需调整 output_line = f"{bracket_content} = {hstep_map[key]};\n" out_f.write(output_line)
关键正则说明
处理input1的正则:
r'^(hstep3_\w+)\s*=\s*(\w+);$'^和$确保匹配整行hstep3_\w+精准匹配左值(如hstep3_num00)\s*=\s*兼容等号两侧的任意空白字符(\w+)捕获右侧的目标值(如a5)
处理input2的正则:
r'^match\s+(hstep3_\w+)\s*=\s*({[^}]+});$'^match\s+匹配行首的match关键字及后续空格{[^}]+}捕获括号内的所有内容(从{到第一个}之间的字符)
注意事项
- 若input文件中存在空白行,
strip()会自动跳过 - 如果值中包含非字母数字的特殊字符,可把正则中的
\w+替换为[^;]+,匹配到分号前的所有内容 - 运行代码前确保文件路径正确,可修改为绝对路径适配不同目录结构
内容的提问来源于stack exchange,提问作者Parine
相关产品推荐
相关产品推荐

