分享

VBA对比两字符串的相似度

 jjls14 2014-11-28

线上有一个用JAVA写的对比两字符串相似度的,据说算法是俄罗斯人写的,还不错。为了在Excel中使用,用VBA改写了一个,放在这里存档。

  1. Private Function min(one As Integer, two As Integer, three As Integer)  
  2.     min = one  
  3.     If (two < min) Then  
  4.      min = two  
  5.     End If  
  6.     If (three < min) Then  
  7.      min = three  
  8.     End If  
  9. End Function  
  10.   
  11. Private Function ld(str1 As String, str2 As String)  
  12. Dim n, m, i, j As Integer  
  13. Dim ch1, ch2 As String  
  14.     n = Len(str1)  
  15.     m = Len(str2)  
  16.     Dim temp As Integer  
  17.     If (n = 0) Then  
  18.         ld = m  
  19.     End If  
  20.     If (m = 0) Then  
  21.         ld = n  
  22.     End If  
  23. Dim d As Variant  
  24. ReDim d(n + 1, m + 1) As Variant  
  25.     For i = 0 To n  
  26.         d(i, 0) = i  
  27.     Next i  
  28.     For j = 0 To m  
  29.         d(0, j) = j  
  30.     Next j  
  31.     For i = 1 To n  
  32.         ch1 = Mid(str1, i, 1)  
  33.         For j = 1 To m  
  34.             ch2 = Mid(str2, j, 1)  
  35.             If (ch1 = ch2) Then  
  36.             temp = 0  
  37.             Else  
  38.                 temp = 1  
  39.             End If  
  40.             d(i, j) = min(d(i - 1, j) + 1, d(i, j - 1) + 1, d(i - 1, j - 1) + temp)  
  41.         Next j  
  42.     Next i  
  43.     ld = d(n, m)  
  44. End Function  
  45.   
  46. Public Function sim(str1 As String, str2 As String)  
  47.     Dim ldint As Integer  
  48.     ldint = ld(str1, str2)  
  49.     Dim strlen As Integer  
  50.     If (Len(str1) >= Len(str2)) Then  
  51.         strlen = Len(str1)  
  52.     Else  
  53.         strlen = Len(str2)  
  54.     End If  
  55.     sim = 1 - ldint / strlen  
  56. End Function  



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多