簡體   English   中英

如何比較兩個字符串並找到相似度的百分比

[英]How to compare two strings and find the percentage of similarity

下面的代碼完成了這項工作,但需要很多時間。 正在比較我已經在 MongoDB 中保存為字符串的兩個 HTML 文件的內容。 並且字符串的長度大約為 30K+,並且有大約 250K+ 條記錄可供比較。 因此,這項工作需要花費大量時間。

有沒有更簡單的方法或插件可以使用並且速度也很快?

private int ComputeCost(string input1, string input2)
{
    if (string.IsNullOrEmpty(input1))
        return string.IsNullOrEmpty(input2) ? 0 : input2.Length;

    if (string.IsNullOrEmpty(input2))
        return string.IsNullOrEmpty(input1) ? 0 : input1.Length;

    int input1Length = input1.Length;
    int input2Length = input2.Length;

    int[,] distance = new int[input1Length + 1, input2Length + 1];

    for (int i = 0; i <= input1Length; distance[i, 0] = i++) ;
    for (int j = 0; j <= input2Length; distance[0, j] = j++) ;

    for (int i = 1; i <= input1Length; i++)
    {
        for (int j = 1; j <= input2Length; j++)
        {
            int cost = (input2[j - 1] == input1[i - 1]) ? 0 : 1;

            distance[i, j] = Math.Min(
                                Math.Min(distance[i - 1, j] + 1, distance[i, j - 1] + 1),
                                distance[i - 1, j - 1] + cost);
        }
    }

    return distance[input1Length, input2Length];
}

根據@Kay Lee,將函數設為靜態並使用 HTML 敏捷包刪除不必要的數據。 並看到了良好的性能改進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM