【问题标题】:How to detect and highlight similar lines in a single code file?如何检测和突出显示单个代码文件中的相似行?
【发布时间】:2021-07-26 20:45:24
【问题描述】:

考虑一个.py 文件,如下所示:

def function1():
    print("Hello world!")
    print("This is 1st function.")

def function2():
    print("Hello world!")
    print("This is 2nd function.")

在上面的例子中,print("Hello world!") 语句在两个函数中是相似的。

如何检测并突出显示单个文件中的此类相似行,以便减少它们?

我尝试了copydetect 库,但它只检测多个文件中的重复项,而不是单个文件中的重复项。

【问题讨论】:

    标签: python duplicates similarity code-duplication


    【解决方案1】:

    您可以编写一个程序,解析每一行并检查每一行的相似性。 有一个名为 difflib 的库,它有一个 SequenceMathcer

    然后你可以用类似的东西检查每条长度相似的线 那个。

    if (SequenceMatcher(line1, line2).ratio() > threshold):
        print("Similar lines found")
    

    该方法为您提供了一个介于 0 和 1 之间的值作为浮点数。 我没有完整的实现,但我认为这将是我检查的方式。

    为了加快比较而不是得到 O(n) = n^2 的复杂度,您可以尝试只比较相似长度的行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 2021-03-01
      相关资源
      最近更新 更多