满足特定条件时替换列表中的元素

问题描述 投票:0回答:1

我正在使用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)

谢谢。

python regex
1个回答
0
投票

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


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)
© www.soinside.com 2019 - 2024. All rights reserved.