NGram近似字符串匹配

介绍

ngram是来自给定序列的n个单位的子序列。 这些单位可以是单词,字符等。例如,短语“ Hello World”的2-gram或bigram是“ He”,“ el”,“ ll”,“ lo”,“ o”,“ W”,“ Wo”,“ or”,“ rl”和“ ld”。

用途

NGram建模通常用于对自然语言进行建模。 它还可用于预测序列中的下一个项目。 IE,给定具有发生频率的NGram模型,您可以预测序列中的下一个项目。

它也用于近似字符串匹配。 基于这样的观察,任何两个相似的字符串都可能共享许多相同的NGram。 因此,它也可用于检测窃。 使用ngram技术的好处之一是索引ngram的能力,因为可以预先计算字符串的ngram。 这与诸如Levenshtein之类的编辑距离算法相反,在该算法中,要比较的字符串和要与之比较的字符串是输入的一部分。 索引ngram的能力可导致更快的搜索,但会导致非常大的索引。

下面的代码是为VBScript编写的,但应直接移植到VBA。

CreateNGram函数将字符串和整数作为输入。 整数定义了您想要用于创建子序列的n-gram的大小。 它输出一个二维数组。 第一项是ngram,第二项是它发生的频率。

CompareNGram函数采用两个ngram数组,并输出一个表示两个数组相似度的double。 返回的数字是两个数组的Dice系数。 系数越高,两个字符串越相似。

Function CreateNGram(strInput, intN)
    Dim arrNGram, intBound, i, j, strGram, didInc, arrTemp 
    If Len(strInput) = 0 Then Exit Function 
    ReDim arrNGram(Len(strInput) + 1, 1)
    strInput = Chr(0) & UCase(Trim(strInput)) & Chr(0)
    intBound = -1 
    For i = 1 To Len(strInput)-intN+1
        strGram = Mid(strInput, i, intN)
        didInc = False 
        For j = 0 To intBound
            If strGram = arrNGram(j, 0) Then
                arrNGram(j, 1) = arrNGram(j, 1) + 1
                didInc = True
                Exit For
            End If
        Next 
        If Not didInc Then
            intBound = intBound + 1
            arrNGram(intBound, 0) = strGram
            arrNGram(intBound, 1) = 1
        End If
    Next 
    ReDim arrTemp(intBound, 1)
    For i = 0 To intBound
        arrTemp(i, 0) = arrNGram(i, 0)
        arrTemp(i, 1) = arrNGram(i, 1)
    Next 
    CreateNGram = arrTemp
End Function 
Function CompareNGram(arr1, arr2)
    Dim i, j, intMatches, intCount1, intCount2 
    intMatches = 0
    intCount1 = 0 
    For i = 0 To UBound(arr1)
        intCount1 = intCount1 + arr1(i, 1)
        intCount2 = 0 
        For j = 0 To UBound(arr2)
            intCount2 = intCount2 + arr2(j, 1) 
            If arr1(i, 0) = arr2(j, 0) Then
                If arr1(i, 1) >= arr2(j, 1) Then
                    intMatches = intMatches + arr2(j, 1)
                Else
                    intMatches = intMatches + arr1(i, 1)
                End If
            End If
        Next
    Next 
    CompareNGram = 2 * intMatches / (intCount1 + intCount2)
End Function

From: https://bytes.com/topic/access/insights/910886-ngram-approximate-string-matching

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值