首页 最新文章网站编程正文

用莱文斯坦距离算法 (Levenshtein Distance)计算两个字符串的相似度的VBA实现

Sub test()

    Dim s1 As String, s2 As String
    
    s1 = Range("a1").Value
    s2 = Range("a2").Value
    L1 = Len(s1)
    L2 = Len(s2)
    M = application.WorksheetFunction.Max(L1, L2)
    ld = Levenshtein(s1, s2)
    
    MsgBox "相似度为:" & Round((1 - ld / M) * 100, 1) & "%"
    
End Sub

Function Levenshtein(ByVal string1 As String, ByVal string2 As String) As Long
    
    Dim i As Long, j As Long
    Dim string1_length As Long
    Dim string2_length As Long
    Dim distance() As Long
    
    string1_length = Len(string1)
    string2_length = Len(string2)
    ReDim distance(string1_length, string2_length)
    
    For i = 0 To string1_length
        distance(i, 0) = i
    Next
    
    For j = 0 To string2_length
        distance(0, j) = j
    Next
    
    For i = 1 To string1_length
        For j = 1 To string2_length
        
            If Asc(Mid$(string1, i, 1)) = Asc(Mid$(string2, j, 1)) Then
                distance(i, j) = distance(i - 1, j - 1)
            Else
                distance(i, j) = APPlication.WorksheetFunction.Min(distance(i - 1, j) + 1, distance(i, j - 1) + 1, distance(i - 1, j - 1) + 1)
            End If
            
        Next
    Next
    
    Levenshtein = distance(string1_length, string2_length)
    
End Function

 

#转载请注明出处!

评论

觉得有用就打赏吧
关注本站公众号,享受更多服务!
联系方式
QQ:########
地址:中国·辽宁
Email:2727987445#qq.com
Copyright ©2015-2021.Powered by 云水客 | 网站地图 | 辽ICP备14000512号-5