簡體   English   中英

在C#中測量兩個字符串的語義相似性

[英]Measuring the semantic similarity of two strings in c#

我一直在使用Levenstein距離來測量兩個字符串的相似度。

int ComputeLevenshteinDistance(string source, string target)
{
    if ((source == null) || (target == null)) return 0;
    if ((source.Length == 0) || (target.Length == 0)) return 0;
    if (source == target) return source.Length;

    int sourceWordCount = source.Length;
    int targetWordCount = target.Length;

    // Step 1
    if (sourceWordCount == 0)
        return targetWordCount;

    if (targetWordCount == 0)
        return sourceWordCount;

    int[,] distance = new int[sourceWordCount + 1, targetWordCount + 1];

    // Step 2
    for (int i = 0; i <= sourceWordCount; distance[i, 0] = i++);
    for (int j = 0; j <= targetWordCount; distance[0, j] = j++);

    for (int i = 1; i <= sourceWordCount; i++)
    {
        for (int j = 1; j <= targetWordCount; j++)
        {
            // Step 3
            int cost = (target[j - 1] == source[i - 1]) ? 0 : 1;

            // Step 4
            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[sourceWordCount, targetWordCount];
}

但我想修改或編寫新代碼,以給出百分比的方式測量兩個字符串的語義相似性。

我試圖在Web上搜索一些代碼示例,但是很難找到一個具有語義相似性度量功能的簡單示例。

有什么簡單明了的方法?

我本人已使用該算法來找到最接近的字符串。 在ICR / OCR文檔中,它非常有用。 要對字符串進行排序,我必須按相似性對字符串進行排序,僅基於編輯距離對輸入進行排序是不夠的。 在對兩個字符串進行歸一化的情況下,我計算出兩個給定字符串之間的最大編輯距離等於最長字符串的長度,而最小值則為零。 因此,我剛剛將編輯距離除以最大距離,將其轉換為百分比。

這是一個幼稚的解決方案,但效果非常好。 在ICR / OCR中,我們有一些誤報,例如h變為lnm變為rn ,等等...我不必擔心它們,現在不再擔心。

PS:就我而言,字符串標准化是刪除所有符號,然后轉換為大寫ASCII字母。

暫無
暫無

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

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