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

标签 python algorithm sorting duplicates similarity

我有一个包含很多消息的文件。每行一条独特的消息,其结构彼此相似,但略有修改。一个例子如下:

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}

最佳答案

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

[{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)

关于Python:如何删除重复/相似的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55702217/

相关文章:

python - 使用 Flask-appengine-template 时出现奇怪的 KeyProperty 失败

algorithm - 部分排序为 N 个未排序组的高效算法

java - 在选择排序项目中,10 个元素的数组仅接受 5 个整数

python - 如何 append 到AWS S3上的json文件

python - PyCharm 中的 "executable not specified"错误

algorithm - 在钟形值列表中找到最大值的快速算法

javascript - AngularJS 中的自定义排序

javascript - 比较对象并仅获取所有对象中存在的对象

python - Paramiko Expect - 拖尾

php - 我们如何在 php 中突出显示完整单词和部分单词?