首页 > 解决方案 > 检测推文是否相似的功能

问题描述

我正在尝试在 VBA 中创建一个函数,该函数采用 2 个字符串和一个阈值(十进制形式的百分比),如果字符串包含的相同单词的百分比高于阈值,则返回 true。这是我到目前为止的代码...

Function isDup(tweet1 As String, tweet2 As String, threshold As Double) As Boolean
    'Declare variables to store words from each tweet
    Dim C1 As String
    Dim C2 As String

    'Use split function to split each tweet into single words. The " " is the delimiter, each space creates a new word
    C1 = Split(tweet1, " ")
    C2 = Split(tweet2, " ")

    'Loop through each word from tweet1 and each word from tweet2
    For i = LBound(C1) To UBound(C1)
        For j = LBound(C2) To UBound(C2)
            'Declare variable to store result from StrComp Function
            Dim Cresult As Double

            'Use StrComp Function to compare the current word from tweet1 to the current word from tweet2
            Cresult = StrComp(i, j, vbTextCompare)
        Next i
    Next j

    'Use If Then to return true if the tweets are more similar than the percentage given by the threshold
    If Cresult > threshold Then
    isDup = True

End Function

我对 VBA 很陌生,所以有一些错误,特别是我一直遇到 Expected: Array Error。任何帮助将不胜感激,谢谢!

标签: arraysexcelvbanested-loops

解决方案


这是一个快速重写,修复了我在上面的评论中提到的内容。如果这不是你所追求的,它应该让你进入球场。

Function isDup(tweet1 As String, tweet2 As String, threshold As Double) As Boolean
    'Declare variables to store words from each tweet
    Dim C1 As Variant
    Dim C2 As Variant

    'Use split function to split each tweet into single words. The " " is the delimiter, each space creates a new word
    C1 = Split(tweet1, " ")
    C2 = Split(tweet2, " ")

    'Declare variable to store result from StrComp Function
    Dim Cresult As Double

    'Loop through each word from tweet1 and each word from tweet2
    For i = LBound(C1) To UBound(C1)
        For j = LBound(C2) To UBound(C2)

            'Use StrComp Function to compare the current word from tweet1 to the current word from tweet2
            If StrComp(C1(i), C2(j), vbTextCompare) = 0 Then
                Cresult = Cresult + 1
            End If
        Next j
    Next i

    'Use If Then to return true if the tweets are more similar than the percentage given by the threshold
    If Cresult > threshold Then
        isDup = True
    End If

End Function

推荐阅读