如何在列表中找到最接近的字符串

3

如何在列表中找到最接近的字符串:

 var list = new List<string>
 {
    "hello how are you",
    "weather is good today",
    "what is your name",
    "what time is it",
    "what is your favorite color",
    "hello world",
    "how much money you got",
    "where are you",
    "like you"
 };

如果更新后的输入为:

  string input = "how are you";

还有一个类型错误:

  string input = "how are ytou";

对于这两种情况,获取以下内容会很有帮助:
hello how are you
where are you

甚至可以得到这个结果:
hello how are you
where are you
how much money you got

或者至少只是:
hello how are you

我需要这个来避免用户请求中的最小类型错误以生成响应。


它总是关于单词中匹配字符的百分比,这些字符绽放成单词的顺序。略高于基本的正则表达式能力。 - user557597
@Wiktor Stribiżew 修改了 - user6841064
2个回答

6
一个简单的方法是使用 String.Compare 获取两个比较对象之间的词法关系。将可用的项目与输入进行比较后排序,并选择最佳匹配项。
string bestMacht = list.OrderBy(s => string.Compare(s, input)).First();

这只是第一步,因为单词的顺序应该被忽略。让我们将其改进为完整的解决方案。在分割字符串后。

string[] splittedInput = input.Split(' ');

您可以使用IEqualityComparer来比较单词。您可以自由定义每个单词允许失败的字符数(在本例中为2)。

private class NearMatchComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return string.Compare(x, y) < 2;
    }

    public int GetHashCode(string obj)
    {
        return obj.GetHashCode();
    }
}

使用该比较器来比较输入词和字典中的单词。如果两个单词(根据要求进行定义)匹配(无论顺序如何),则选择该字符串。
List<string> matches = list.Where(s => s.Split(' ')
    .Intersect(splittedInput, new NearMatchComparer()).Count() >= 2)
    .ToList();

结果是潜在匹配项的列表。

你好,所以你的输出是 string input = "how are you"; 的结果是: hello how are you, how much money you got, where are youstring input = "how are ytou"; 的结果只有 hello how are you。如果我对第一个结果使用 OrderBy,它等同于自己的结果。看起来这是获取这种解决方案结果的正确方式,即使它与理论上避免字符串中包含单个相等单词的输出不相等,并且在包含组合的单词中具有类型错误时也会执行相同操作。由于我并没有直接要求解决方案,所以我打算标记它,因为它回答了我的目标。 - user6841064

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接