[英]c#: How to find which string from a list of strings has the most matching characters in a row to a sample string?
[英]Using C#, From a list of strings, how do we find the one that most closely matches a test string?
給定一個字符串列表:
strings[0] = "Mary Brown";
strings[1] = "Sally Green";
strings[2] = "Lucy Purple";
給定輸入字符串:
x = "Mary Brown is a nice person";
如何確定第一個字符串是最匹配x
的字符串,而不是其余字符串?
在我的情況下,不知道字符串將以答案開頭。 也可能是個詞。 可以說“馬克·布朗是一個好人”而不是“瑪麗·布朗是一個好人”,但是“瑪麗·布朗”仍然是最接近的匹配者。
注意:答案不必使用正則表達式。 我在尋找C#答案。
我將搜索文本和輸入按空格分開,然后找到匹配單詞的數量。 按計數降序排列,然后取文字。
var inputs = new[] { "Mary Brown", "Sally Green", "Lucy Purple" };
var searchText = "Mary Brown is a nice person";
var words = searchText.Split(' ');
var result = inputs.Select(text => new
{
MatchCount = text.Split(' ')
.Sum(input => words.Where(word => word == input).Count()),
Text = text
})
.OrderByDescending(a => a.MatchCount)
.Select(a => a.Text)
.DefaultIfEmpty()
.First();
輸出:
Mary Brown
PS
為了獲得更好的結果,可以使用類似於本文的字符串相似度算法替換word == input
部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.