在字符串(段落)中匹配大型短语字典中的项目的有效方法是什么

本文关键字:字典 项目 有效 是什么 方法 短语 字符串 段落 大型 | 更新日期: 2023-09-27 18:37:07

有没有办法通过.Net aframework(或者有人写过类似的东西)在传递字符串和字典对象时获取匹配数组?

首先一些背景

我需要

有运动队的csv文件,我将其加载到字典对象中,例如...

Team, Variants
Manchester United, Manchester United
Manchester United, manutd
Manchester United, man utd
Manchester United, manchester utd
Manchester United, mufc
Aston Villa, Aston Villa
Aston Villa, avfc
Newcastle United, Newcastle United
Newcastle United, toon army

现在我想看看字符串是否包含该字典中的任何短语。

示例字符串...

"I wonder if man utd, aston villa andthe toon army will exist in this string"

现在我想返回匹配的 n 个字符串数组,示例输出如下:

["Manchester United","Aston Villa", "Newcastle United"]

我目前正在使用正则表达式来拆分字符串中的单词。然后我循环遍历字符串中的每个单词并针对字典进行测试(这里的注意是代码确实有效,但只有单个单词而不是短语,这是由于正则表达式)

public static List<string> CheckStringWithDictionary(string input, Dictionary<string, string> dic, int minimumLength)
{
    List<string>lst = new List<string>();
    string myValue = "";
        foreach (Match match in RegexSplitStringToArray(input, minimumLength))
        {
            if (dic.TryGetValue(match.Value, out myValue))
                lst.Add(myValue);
        }
    return lst;
}
public static MatchCollection RegexSplitStringToArray(string input, int minLength)
{
    Regex csvSplit = new Regex("(''w{3,})", RegexOptions.Compiled);
    return csvSplit.Matches(input);
}

循环字符串而不是字典的原因是字典将包含超过 10,000+ 个项目,因此在循环遍历该字符串方面效率非常低。

感谢您到目前为止的patiece,现在来回答这个问题...

有没有办法通过.Net aframework(或者有人写过类似的东西)在传递字符串和字典对象时获取匹配数组?

谢谢大家

在字符串(段落)中匹配大型短语字典中的项目的有效方法是什么

我会使用 LINQ 来实现这一点:

 string input = "I wonder if man utd, aston villa andthe toon army will exist in this string";
 List<string> matches = dic.
                           .Where(kvp => input.Contains(kvp.Key))
                           .Select(kvp => kvp.Value)
                           .ToList();

这仍然有效地循环遍历字典,但如果您需要处理多个单词选项,这可能比大多数替代方案更好,即使使用大型字典也是如此。

使用标准字典和字符串比较不会更快。为了获得真正的性能,您需要Aho-Corassick算法的口径。本质上,你用字典构建了一个特殊的树并与之匹配。该算法在输入大小和字典大小方面是线性的。