在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
相关推荐
xiaopai9455 小时前
用WPS做EPC资金计划表:什么时候是表格问题,什么时候已经变成数据关系问题?
wps·建米软件·epc资金计划
扬帆破浪9 小时前
文档自动检查:用 Claude Code、OpenClaw 审 WPS 文件:预览、批注、改正文
运维·服务器·wps
asdzx6712 小时前
Java 实战:基于 Spire.Doc 高效提取 Word 文档文本与图片
java·c#·word
VBAMatrix12 小时前
表格导航!实现Word合并附注与多个Excel的数据同步
word·excel·审计报告·审计·会计师事务所·报告工具
DS随心转小程序1 天前
文心文字怎么转为 word?告别繁琐排版操作,AI 导出鸭一站式完成文档转换工作
人工智能·word·豆包·deepseek·ai导出鸭
AI导出鸭2 天前
怎么让千问做表格?AI导出鸭苹果版将千问输出的管道表格智能解析为二维结构,一键导出为Excel或Word标准表格。
人工智能·chatgpt·word·excel·ai导出鸭
zyplayer-doc2 天前
zyplayer-doc企业知识库能做什么:从文档创建、权限管理到AI问答的完整能力
大数据·javascript·数据库·人工智能·pdf·word
stitchshaw3 天前
wps:在一张PPT中画多个子图
powerpoint·wps
PythonFun3 天前
告别VLOOKUP!XLOOKUP模糊匹配实操指南
wps
灵析表格4 天前
灵析表格手机号处理函数深度分析报告
前端·网络·json·wps·灵析表格·excel公式盒子