C#在两个字符串之间查找匹配单词的百分比



我有一个字符串,我想将其与字符串列表进行比较,以找到最佳匹配。

例如,

string search = "Orange Black Red One Five"

字符串列表可能包含以下

l[0] = "Orange Seven Three Black"
l[1] = " Nine Eight Seven Six"
l[2] = " Black Blue Purple Red Five Four Nine Ten"
l[0] contains 2 matches
l[1] contains 0 matches
l[2] contains 3 matches

因此程序会选择l[2]作为最佳匹配,匹配率为60%
我该如何比较这样的两个字符串?

    var s = search.Split(new string[] { " "}, StringSplitOptions.RemoveEmptyEntries);
    var res1 = (from string part in l
        select new
        {
            list = part,
            count = part.Split(new char[] {' '}).Sum(p => s.Contains(p) ? 1 : 0)
        }).OrderByDescending(p=> p.count).First();
    Console.Write(res1.count);
  1. 将字符串拆分为数组
  2. 确定匹配的数量
  3. 分割
  4. 利润

代码:

double Compare(string a, string b)
{
    var aWords = a.Split(' ');
    var bWords = b.Split(' ');
    double matches = (double)aWords.Count(x => bWords.Contains(x));
    return matches / (double)aWords.Count();
}

编辑:或者,如果你只是想获得匹配计数。。。

int Matches(string a, string b)
{
    var aWords = a.Split(' ');
    var bWords = b.Split(' ');
    return aWords.Count(x => bWords.Contains(x));
}

相关内容

  • 没有找到相关文章

最新更新