一个关于 Python difflib 的问题,两个待比较内容,位置换一下,为什么结果差这么多?

340 天前
 heyjei

现在需要对学生提交的代码,进行简单的相似度检测。但是在测试过程中发现了一个问题。

简化之后的测试代码在下面

对两段比较相似的 CSS 代码进行相似度检测,difflib.SequenceMatcher(None, css1, css2).ratio() 使用这个函数检测的时候,css1 和 css2 参数位置换一下,结果相似度居然一个是 97%,一个 18%,差点产生了一条漏网之鱼。加上 autojunk=False 可以解决这个问题,但是这个检测速度太慢了,所以初步估计应该是这个“自动垃圾启发式计算”的问题,但是具体原因没有深究,有人遇到过同样的问题吗?

import difflib


css1 = '''
.header img{
    height: 35px;
    
}
.header{
    display: flex;
    margin-bottom: 15px;
    justify-content: space-between;
}
.header-content{
    align-items: center;
    margin-left: 20px;
}
.photo1{
   
    text-align: center;
}

.photo img{
    height:30px;
}
.container{
    width: 750px;
    margin-left: auto;
    margin-right: auto;
}
.cc{
    justify-content: space-between;
    display: flex;
}
'''

css2 = '''
.header img{
    height: 30px;

}
.header{
    display: flex;
    margin-bottom: 10px;
    justify-content: space-between;
}
.header-content{
    align-items: center;
    margin-left: 20px;
}
.photo1{

    text-align: center;
}

.photo img{
    height:30px;
}
.container{
    width: 700px;
    margin-left: auto;
    margin-right: auto;
}
.po{
    justify-content: space-between;
    display: flex;
}
'''
ratio1 = difflib.SequenceMatcher(None, css1, css2).ratio()
ratio2 = difflib.SequenceMatcher(None, css2, css1).ratio()

print(ratio1)
print(ratio2)

''' 下面是输出结果
0.969173859432799
0.18249075215782984
'''
171 次点击
所在节点    问与答
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/948670

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX