Python:如何删除重复/类似的行

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

我有一个包含大量消息的文件。每行都是一个独特的消息,它们的结构相似,略有修改。一个例子如下:

Error number 609 at line 10
Error number 609 at line 22
Error string "foo" at line 11
Error string "bar" at line 14

并希望输出类似于:

Error number 609 at line 10
Error string "foo" at line 11

它们是“相同”类型的错误。

我设法删除类似的行,但我遇到的问题是我必须循环遍历文件中的每一行,直到它没有更多的“重复”。

我目前拥有的:

from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

lst = open("result.txt").readlines()
print(len(lst))
for i in lst:
    for index, line in enumerate(lst):
        try:
            if similar(lst[index],lst[index + 1]) > 0.8:
                lst.pop(index)
        except:
            pass

print(len(lst))

但这不是一个确定的方法,因为它可能是一个过度的循环次数,或者如果文件真的很大,有许多“相同”的行可能还不够。

编辑:

一个文件中许多类型的消息之一的更准确的例子将是:

[{TYPE}] Timeout after {miliseconds} millis, source ref: {random-number}, system: {system}, delivered {system}: , current {system}: {time}
python algorithm sorting duplicates similarity
2个回答
1
投票

假设输入文件中的每个条目都采用以下格式......

[{TYPE}] Timeout after {miliseconds} millis, source ref: {random-number}...
lst = open("result.txt").readlines()

pretoken = "["
posttoken = "]"

foundTypes = []
log = []

for line in lst:
    foundType = ""
    for letter in line:
        if letter == pretoken: pass
        elif letter == posttoken: break
        else: foundType += letter

    if foundType not in foundTypes:
        foundTypes.append(foundType)
        log.append(line)

print(log)

1
投票

您只需要逐行打开并读取日志文件。

a=b=None
with open('result.txt') as infile:
    if a == None:
        a = infile.readline()
    b = infile.readline()
    while a:
        a = infile.readline()
        print('proc similar(a,b)')
        b = a
© www.soinside.com 2019 - 2024. All rights reserved.