2017年5月7日 星期日

使用Excel建立自定義函數,計算文字的Edit Distance

使用Excel建立自定義函數,計算文字的Edit Distance
Levenshtein("saturday","sunday") = 3

步驟:
1. Excel>開發人員>Visual Basic>插入>模組
2. 貼上以下程式碼(Levenshtein是Function Name)
3. 檔案>另存新檔>Excel啟用巨集的活頁簿(*.xlsm)
4. 到同一個Excel檔的任一工作表的儲存格,輸入以下文字
     =Levenshtein("saturday","sunday")
5. 該儲存格就會呈現3


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


http://stackoverflow.com/questions/4243036/levenshtein-distance-in-excel

https://support.office.com/en-us/article/Create-Custom-Functions-in-Excel-2007-2f06c10b-3622-40d6-a1b2-b6748ae8231f#bmcreatingsimple

https://en.wikipedia.org/wiki/Levenshtein_distance

沒有留言 :