V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
heyjei
V2EX  ›  问与答

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

  •  
  •   heyjei · 329 天前 · 167 次点击
    这是一个创建于 329 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    对两段比较相似的 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
    '''
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4281 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:57 · PVG 08:57 · LAX 17:57 · JFK 20:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.