Levenshtein距离VBA [英] Levenshtein Distance in VBA

查看:340
本文介绍了Levenshtein距离VBA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有excel表与数据,我想得到他们之间的Levenshtein距离。我已经尝试导出为文本,从脚本(php)读入,运行Levenshtein(计算Levenshtein距离),再次保存到excel。



但我正在寻找一种在VBA中编程计算Levenshtein距离的方法。我该怎么做?

解决方案

翻译自维基百科

  Option Explicit 
公共函数Levenshtein(s1 As String,s2 As String)

Dim i As Integer
Dim j As Integer
Dim l1 As Integer
Dim l2 As Integer
Dim d()As Integer
Dim min1 As Integer
Dim min2 As Integer

l1 = Len(s1)
l2 = Len(s2)
ReDim d(l1,l2)
对于i = 0到l1
d(i,0)= i
下一个
对于j = 0到l2
d(0,j)= j
Next
对于i = 1至l1
对于j = 1至l2
如果Mid(s1,i,1)= Mid(s2,j,1)然后
d i,j)= d(i-1,j-1)
Else
min1 = d(i - 1,j)+ 1
min2 = d(i,j - + 1
如果min2 < min1然后
min1 = min2
End If
min2 = d(i - 1,j - 1)+ 1
如果min2 < min1然后
min1 = min2
End If
d(i,j)= min1
End If
Next
Next
Levenshtein = d l1,l2)
结束功能

?Levenshtein(星期六,星期日)



3


I have excel sheet with data which I want to get Levenshtein Distance between them. I already tried to export as text, read in from script (php), run Levenshtein (calculate Levenshtein Distance), save it to excel again.

But I am looking for a way to programatically calculate a Levenshtein Distance in VBA. How would I go about doing so?

解决方案

Translated from Wikipedia :

Option Explicit
Public Function Levenshtein(s1 As String, s2 As String)

Dim i As Integer
Dim j As Integer
Dim l1 As Integer
Dim l2 As Integer
Dim d() As Integer
Dim min1 As Integer
Dim min2 As Integer

l1 = Len(s1)
l2 = Len(s2)
ReDim d(l1, l2)
For i = 0 To l1
    d(i, 0) = i
Next
For j = 0 To l2
    d(0, j) = j
Next
For i = 1 To l1
    For j = 1 To l2
        If Mid(s1, i, 1) = Mid(s2, j, 1) Then
            d(i, j) = d(i - 1, j - 1)
        Else
            min1 = d(i - 1, j) + 1
            min2 = d(i, j - 1) + 1
            If min2 < min1 Then
                min1 = min2
            End If
            min2 = d(i - 1, j - 1) + 1
            If min2 < min1 Then
                min1 = min2
            End If
            d(i, j) = min1
        End If
    Next
Next
Levenshtein = d(l1, l2)
End Function

?Levenshtein("saturday","sunday")

3

这篇关于Levenshtein距离VBA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆