我正在寻找一种将字符串与字符串数组进行比较的方法。当然,进行精确搜索非常容易,但我希望我的程序能够容忍拼写错误、丢失部分字符串等。

是否有某种框架可以执行此类搜索?我想到搜索算法将按匹配百分比或类似的内容返回一些结果。

有帮助吗?

解决方案

您可以使用 Levenshtein距离算法

“两个字符串之间的Levenshtein距离被定义为一个串转换成另一个必要的修改的最小数目,与可允许的编辑操作是插入,缺失,或单个字符的替换。” - Wikipedia.com

这是一个从 dotnetperls.com

using System;

/// <summary>
/// Contains approximate string matching
/// </summary>
static class LevenshteinDistance
{
    /// <summary>
    /// Compute the distance between two strings.
    /// </summary>
    public static int Compute(string s, string t)
    {
        int n = s.Length;
        int m = t.Length;
        int[,] d = new int[n + 1, m + 1];

        // Step 1
        if (n == 0)
        {
            return m;
        }

        if (m == 0)
        {
            return n;
        }

        // Step 2
        for (int i = 0; i <= n; d[i, 0] = i++)
        {
        }

        for (int j = 0; j <= m; d[0, j] = j++)
        {
        }

        // Step 3
        for (int i = 1; i <= n; i++)
        {
            //Step 4
            for (int j = 1; j <= m; j++)
            {
                // Step 5
                int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;

                // Step 6
                d[i, j] = Math.Min(
                    Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                    d[i - 1, j - 1] + cost);
            }
        }
        // Step 7
        return d[n, m];
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(LevenshteinDistance.Compute("aunt", "ant"));
        Console.WriteLine(LevenshteinDistance.Compute("Sam", "Samantha"));
        Console.WriteLine(LevenshteinDistance.Compute("flomax", "volmax"));
    }
}

您可能实际上宁愿使用 Damerau-Levenshtein距离算法,这也允许将转置的字符,这是在数据输入共同的人为错误。你会发现它的 rel="noreferrer">这里的C#实现。

其他提示

.NET 框架中没有任何东西可以帮助您完成此开箱即用的操作。

最常见的拼写错误是字母是单词的正确语音表示,但不是单词的正确拼写。

例如,可以认为这些词 swordsord (是的,这是一个词)具有相同的音根(当您发音时,它们听起来相同)。

话虽如此,您可以使用多种算法将单词(甚至拼写错误的单词)翻译为语音变体。

第一个是 声音指数. 。实现起来相当简单,并且有相当多的 该算法的 .NET 实现. 。它相当简单,但它为您提供了可以相互比较的真实价值。

另一个是 变音位. 。虽然我找不到 Metaphone 的本机 .NET 实现,但提供的链接包含指向许多可以转换的其他实现的链接。最容易转换的可能是 Metaphone算法的Java实现.

值得注意的是,Metaphone 算法已经过修订。有 双变音位 (其中有一个 .NET 实现) 和 变音位3. 。Metaphone 3 是一个商业应用程序,但在针对常见英语单词的数据库运行时,其准确率高达 98%,而 Double Metaphone 算法的准确率仅为 89%。根据您的需要,您可能需要寻找(在 Double Metaphone 的情况下)或购买(在 Metaphone 3 的情况下)算法源,并通过 P/Invoke 层转换或访问它(有 C++ 实现)盛产)。

Metaphone 和 Soundex 的不同之处在于 Soundex 生成固定长度的数字键,而 Metaphone 生成不同长度的键,因此结果会不同。最后,两者都会为您进行相同的比较,您只需根据您的要求和资源(当然还有对拼写错误的不容忍程度)找出最适合您的需求的比较。

下面是编辑距离的方法,使用少得多的存储器,同时产生相同的结果的实现。这是伪代码的C#适应在此维基百科文章发现下的“迭代具有两个矩阵行”的标题。

public static int LevenshteinDistance(string source, string target)
{
    // degenerate cases
    if (source == target) return 0;
    if (source.Length == 0) return target.Length;
    if (target.Length == 0) return source.Length;

    // create two work vectors of integer distances
    int[] v0 = new int[target.Length + 1];
    int[] v1 = new int[target.Length + 1];

    // initialize v0 (the previous row of distances)
    // this row is A[0][i]: edit distance for an empty s
    // the distance is just the number of characters to delete from t
    for (int i = 0; i < v0.Length; i++)
        v0[i] = i;

    for (int i = 0; i < source.Length; i++)
    {
        // calculate v1 (current row distances) from the previous row v0

        // first element of v1 is A[i+1][0]
        //   edit distance is delete (i+1) chars from s to match empty t
        v1[0] = i + 1;

        // use formula to fill in the rest of the row
        for (int j = 0; j < target.Length; j++)
        {
            var cost = (source[i] == target[j]) ? 0 : 1;
            v1[j + 1] = Math.Min(v1[j] + 1, Math.Min(v0[j + 1] + 1, v0[j] + cost));
        }

        // copy v1 (current row) to v0 (previous row) for next iteration
        for (int j = 0; j < v0.Length; j++)
            v0[j] = v1[j];
    }

    return v1[target.Length];
}

下面是给你的百分比相似性的函数。

/// <summary>
/// Calculate percentage similarity of two strings
/// <param name="source">Source String to Compare with</param>
/// <param name="target">Targeted String to Compare</param>
/// <returns>Return Similarity between two strings from 0 to 1.0</returns>
/// </summary>
public static double CalculateSimilarity(string source, string target)
{
    if ((source == null) || (target == null)) return 0.0;
    if ((source.Length == 0) || (target.Length == 0)) return 0.0;
    if (source == target) return 1.0;

    int stepsToSame = LevenshteinDistance(source, target);
    return (1.0 - ((double)stepsToSame / (double)Math.Max(source.Length, target.Length)));
}

您另一种选择是比较音素使用探测法或音位。我刚刚完成了两种算法的文章,呈现C#代码。您可以在 http://www.blackbeltcoder.com/查看物品/算法/音标字符串比较与 - 同音

下面是两种方法计算 Levenshtein距离串之间的。

  

两个字符串之间的Levenshtein距离被定义为一个串转换成另一个必要的修改的最小数目,与可允许的编辑操作是插入,缺失,或单个字符的替换。

一旦有了结果,你需要定义要为匹配或不阈值所使用的值。运行在一堆样本数据的函数来得到它是如何工作来帮助一个好主意,你的特定阈值决定。

    /// <summary>
    /// Calculates the Levenshtein distance between two strings--the number of changes that need to be made for the first string to become the second.
    /// </summary>
    /// <param name="first">The first string, used as a source.</param>
    /// <param name="second">The second string, used as a target.</param>
    /// <returns>The number of changes that need to be made to convert the first string to the second.</returns>
    /// <remarks>
    /// From http://www.merriampark.com/ldcsharp.htm
    /// </remarks>
    public static int LevenshteinDistance(string first, string second)
    {
        if (first == null)
        {
            throw new ArgumentNullException("first");
        }
        if (second == null)
        {
            throw new ArgumentNullException("second");
        }

        int n = first.Length;
        int m = second.Length;
        var d = new int[n + 1, m + 1]; // matrix

        if (n == 0) return m;
        if (m == 0) return n;

        for (int i = 0; i <= n; d[i, 0] = i++)
        {
        }

        for (int j = 0; j <= m; d[0, j] = j++)
        {
        }

        for (int i = 1; i <= n; i++)
        {

            for (int j = 1; j <= m; j++)
            {
                int cost = (second.Substring(j - 1, 1) == first.Substring(i - 1, 1) ? 0 : 1); // cost
                d[i, j] = Math.Min(
                    Math.Min(
                        d[i - 1, j] + 1,
                        d[i, j - 1] + 1),
                    d[i - 1, j - 1] + cost);
            }
        }

        return d[n, m];
    }

可以找到在开源 CommonLibrary.NET项目同音的实现和Levenshtein距离的算法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top