如何使用Python调整文本文件指定行内的字符串位置
实现代码
import re # 匹配所有key="value"格式属性的正则 attr_regex = re.compile(r'(\w+)="([^"]+)"') with open('inputfile.txt', 'r', encoding='utf-8') as in_file, open('fileout.txt', 'w', encoding='utf-8') as out_file: prev_buffer = '' for raw_line in in_file: current_line = raw_line.rstrip('\n') # 处理跨行的属性拼接 if prev_buffer: current_line = f"{prev_buffer} {current_line.lstrip()}" prev_buffer = '' # 处理product开头的行 if current_line.startswith('product name='): # 提取所有属性存入字典 attr_dict = dict(attr_regex.findall(current_line)) # 判断是否包含control_type if 'control_type' in attr_dict: new_line = f'product name="{attr_dict["name"]}" sys_name="{attr_dict["sys_name"]}" control_type="{attr_dict["control_type"]}"\n' else: new_line = f'product name="{attr_dict["name"]}" sys_name="{attr_dict["sys_name"]}" act_ferq="{attr_dict["act_ferq"]}" s_c="{attr_dict["s_c"]}"\n' out_file.write(new_line) # 单独一行的sys_name属性,缓存到下一行拼接 elif current_line.startswith('sys_name="'): prev_buffer = current_line # 其他行直接原样输出 else: out_file.write(raw_line)
逻辑说明
- 增加缓存机制处理拆分到两行的属性内容,避免因为换行导致属性匹配遗漏
- 用正则提取所有
key="value"格式的属性,存入字典后按需重组,比直接做字符串替换更灵活 - 按需求分两种场景生成新的product行:
- 包含
control_type时,删除s_c和act_ferq两个属性,按name → sys_name → control_type的顺序拼接 - 不包含
control_type时,按name → sys_name → act_ferq → s_c的顺序拼接所有属性
- 包含
- 非product开头的非拆分属性行直接原样写入输出文件
内容的提问来源于stack exchange,提问作者rebel095
相关产品推荐
相关产品推荐

