如何在列表中找到最接近的字符串
How to find closest string in list
如何在列表中找到最接近的字符串:
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
我需要它来避免用户请求做出响应时出现最小类型错误。
一个简单的方法是使用 String.Compare
来获得
lexical relationship between the two comparands
在与输入的比较后订购您可用的商品,并选择最匹配的商品
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();
}
}
使用这个比较器比较输入的单词和你的字典。如果两个词(按要求定义)匹配(无论顺序如何)select 字符串。
List<string> matches = list.Where(s => s.Split(' ')
.Intersect(splittedInput, new NearMatchComparer()).Count() >= 2)
.ToList();
结果是一个潜在匹配列表。
我会使用 Levenshtein 距离。这为您提供了不同字符串的价值。只需选择您设置的最小距离。
How to calculate distance similarity measure of given 2 strings?
如何在列表中找到最接近的字符串:
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
我需要它来避免用户请求做出响应时出现最小类型错误。
一个简单的方法是使用 String.Compare
来获得
lexical relationship between the two comparands
在与输入的比较后订购您可用的商品,并选择最匹配的商品
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();
}
}
使用这个比较器比较输入的单词和你的字典。如果两个词(按要求定义)匹配(无论顺序如何)select 字符串。
List<string> matches = list.Where(s => s.Split(' ')
.Intersect(splittedInput, new NearMatchComparer()).Count() >= 2)
.ToList();
结果是一个潜在匹配列表。
我会使用 Levenshtein 距离。这为您提供了不同字符串的价值。只需选择您设置的最小距离。
How to calculate distance similarity measure of given 2 strings?