首页 > 解决方案 > 满足特定条件时替换列表中的元素

问题描述

我正在研究一个 python 脚本,目前如果一个定义的文本文件具有与列表匹配的某些短语,它将从文件中删除它们。

相关列表代码片段如下:

replacements = {'pc-123456 alert good-name-here':'',
                'pc-123456 alert remove-name-here':'',
}

{ 中的前半部分是警报文件中的直接文本,而:'' 是在匹配时从文件中清除文本。目前,这有效。

我需要将以下内容添加到脚本中的替换列表中,其中:

replacements = {'12-Dec-19 00:00 pc-123456 alert good-name-here':'',
                '12-Dec-19 00:01 pc-123456 alert remove-name-here':'',
                '12-Dec-19 00:01 pc-234567 alert remove-name-here':'',
}

但我想删除任何定义为“remove-name-here”的详细信息(包括日期/时间、设备名称等),即使警报将在超过 2 个设备上发生(例如 pc-123456、pc -2345678、pc-356435、pc-4563255)等。

如果脚本为相同的警报名称选择不同的设备名称并删除时间戳(当前未在替换列表中定义),那么删除整个文本行的最简单方法是什么?

其余代码如下:

lines = []
with open('path/to/file.txt') as infile:
    for line in infile:
        for src, target in replacements.items():
            line = line.replace(src, target)
        lines.append(line)

with open('path/to/same/file.txt', 'w') as outfile:
    for line in lines:
        outfile.write(line)

谢谢。

标签: pythonregex

解决方案


如果您知道行尾是什么,则可以执行以下操作:


to_remove_endings = ['to_remove_ending']
lines = []

with open('path/to/file.txt') as infile:
    for line in infile:
        next_line = line
        for ending in to_remove_endings:
            if line.rstrip().endswith(ending):
                next_line = '\n'
                break
        lines.append(next_line)

with open('path/to/same/file.txt', 'w') as outfile:
    for line in lines:
        outfile.write(line)

您还可以查找子字符串:

unwanted = ['substring 1', 'substring 2']
lines = []

with open('path/to/file.txt') as infile:
    for line in infile:
        next_line = line
        for substring in unwanted:
            if substring in line:
                next_line = '\n'
                break
        lines.append(next_line)

with open('path/to/same/file.txt', 'w') as outfile:
    for line in lines:
        outfile.write(line)

推荐阅读