Python脚本优化:删除含指定关键词的行及至/end的所有行
批量跳过关键词区块的Python脚本优化
需求背景
原脚本仅能删除包含指定关键词的单行,现在需要升级逻辑:当检测到ICE_words列表中任意关键词所在的行时,跳过该行及后续所有行,直到遇到包含/end的行,且对每个关键词都执行此规则。
原代码如下:
def remove_line(line, ICE_words): return any([word in line for word in ICE_words]) ICE_words = [ "_Amb_" , "_fuel_", ] with open('Inputs.txt','r') as infile: with open('Outputs.txt','w') as Include_in_A2L: for line in infile: if not remove_line(line, ICE_words): Include_in_A2L.write(line)
示例输入文本:
/begin MEASUREMENT Amb_air_temp "Ambient air temperature" data1 data2 /end MEASUREMENT /begin MEASUREMENT fuel_value "Fuel injection value per stroke" data1 data2 /end MEASUREMENT
优化后的代码
ICE_words = ["_Amb_", "_fuel_"] def should_skip_block(line, ICE_words): return any(word in line for word in ICE_words) with open('Inputs.txt', 'r') as infile, open('Outputs.txt', 'w') as outfile: skip_mode = False for line in infile: if skip_mode: # 检查是否到达区块结尾,到达则退出跳过模式 if "/end" in line: skip_mode = False # 跳过当前行,不写入 continue # 不在跳过模式时,检查是否触发跳过规则 if should_skip_block(line, ICE_words): skip_mode = True continue # 正常写入行 outfile.write(line)
关键逻辑说明
- 用
skip_mode布尔变量标记是否处于“跳过区块”状态 - 循环处理每一行:
- 如果已经在跳过模式:检查是否遇到
/end,遇到就关闭跳过模式;无论如何都不写入当前行 - 如果不在跳过模式:检查当前行是否包含目标关键词,包含则开启跳过模式;否则正常写入该行
- 如果已经在跳过模式:检查是否遇到
- 去掉了原代码中多余的列表推导(
any()直接接生成器表达式更高效)
内容的提问来源于stack exchange,提问作者user26944634
相关产品推荐
相关产品推荐

