在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
相关推荐
weixin_4166600716 小时前
从标记语言到 Word 文档:AI 生成的 Mermaid 与 LaTeX 自动化转换的技术方案解析
word·latex·数学公式·deepseek
昵称暂无11 天前
通过 C# 复制 Word 文档、指定段落、指定节
开发语言·c#·word
专注VB编程开发20年1 天前
WPS 2024 Windows版UI用QT5和自研DirectUI-vba,jsa
qt·vba·wps·jsa·directui
扬帆破浪3 天前
麒麟系统安装察元 WPS AI 文档助手:免费、开源、离线部署说明
人工智能·开源·wps
扬帆破浪3 天前
免费开源的WPS AI 插件,离线安装、多系统与内网模型
人工智能·开源·wps
STRUGGLE_xlf3 天前
AI大模型生成表格粘贴到 Word 后出现双线边框的原因与解决方案
word
weixin_416660073 天前
2026 年 AI 对话转 Word 工具分析:Pandoc、Typora、aitoword 怎么选
人工智能·word
Evonso3 天前
Excel按照日期隔行颜色规则
wps
F_D_Z4 天前
Word Embedding :从分布式假设到神经网络语言模型
分布式·word·embedding
asdzx674 天前
C#:通过模板快速生成 Word 文档
开发语言·c#·word