在Word中,用VBA比较两段文本的相似度

效果1:

去掉字符串中回车,进行改进后效果:

代码:

vbscript 复制代码
Function LevenshteinDistance(s As String, t As String) As Integer
    Dim d() As Integer
    Dim i As Integer
    Dim j As Integer
    Dim cost As Integer

    Dim sLen As Integer
    Dim tLen As Integer

    sLen = Len(s)
    tLen = Len(t)

    ReDim d(sLen, tLen)

    For i = 0 To sLen
        d(i, 0) = i
    Next i

    For j = 0 To tLen
        d(0, j) = j
    Next j

    For i = 1 To sLen
        For j = 1 To tLen
            If mid(s, i, 1) = mid(t, j, 1) Then
                cost = 0
            Else
                cost = 1
            End If

            d(i, j) = GetMinValue(GetMinValue(d(i - 1, j) + 1, d(i, j - 1) + 1), d(i - 1, j - 1) + cost)
        Next j
    Next i

    LevenshteinDistance = d(sLen, tLen)
End Function
Function GetMinValue(ByVal Num1, ByVal Num2)
    Dim MinValue As Double
    MinValue = Num1
    If Num2 < MinValue Then MinValue = Num2
    GetMinValue = MinValue
End Function
Function similarity1(s As String, t As String) As Double
    Dim maxLen As Integer
    Dim dist As Integer
    If Len(s) > Len(t) Then
        maxLen = Len(s)
        
    Else
        maxLen = Len(t)
    End If
    If maxLen = 0 Then
        similarity1 = 1#  ' 如果两个字符串都为空,视为完全相似
        Exit Function
    End If

    dist = LevenshteinDistance(s, t)
    similarity1 = 1# - (dist / maxLen)
End Function

Sub TestSimilarity()
    Dim str1 As String
    Dim str2 As String
    Dim similarity As Double

    str1 = ActiveDocument.Content.Paragraphs(1).Range.text
    str2 = ActiveDocument.Content.Paragraphs(3).Range.text
    str1 = Replace(str1, vbCr, "")
    str2 = Replace(str2, vbCr, "")
    
    similarity = similarity1(str1, str2)
    MsgBox "文本相似度: " & Format(similarity, "0.00%")
End Sub
相关推荐
wqqqianqian1 天前
国产linux系统(银河麒麟,统信uos)使用 PageOffice在线编辑word文件保存数据同时保存文件
linux·word·信创·国产·保存·pageoffice·在线编辑
余子桃1 天前
Python实现markdown文件转word
python·word·markdown
一只特立独行的兔先森1 天前
WordZero:让Markdown与Word文档自由转换的Golang利器
golang·word·word自动化
CodeCraft Studio1 天前
文档处理组件Aspose.Words 25.5全新发布 :六大新功能与性能深度优化
word·aspose·aspose.words·word文档转换
weixin_472339461 天前
python批量解析提取word内容到excel
python·word·excel
俱会一处1 天前
将word文件转为kindle可识别的azw3文件的方法
word
cccl.1 天前
Java在word中指定位置插入图片。
java·word
CodeCraft Studio2 天前
国产化Word处理控件Spire.Doc教程:Java实现HTML 转Word自动化
java·html·word
被放养的研究生2 天前
WPS快速排版
wps
星卯教育tony2 天前
在WPS中如何启用宏VBA wps.vba.exe下载和安装
wps