【问题标题】:Finding sentences contained in other sentences查找其他句子中包含的句子
【发布时间】:2015-02-23 02:28:15
【问题描述】:

给定两个句子列表,我如何找到句子对,其中一个句子中的所有单词都包含在另一个句子中?

例子:

List1: {"free bar", "hello world", "foo"}
List2: {"hello there world", "foobar", "bar"}

输出应该告诉我 List1 中的“hello world”包含在 List2 中的“hello there world”中,而 List2 中的“bar”包含在 List1 中的“free bar”中。另一方面,“foo”和“foobar”不匹配。

我尝试过使用 c# 和 LINQ 运行所有内容并匹配正则表达式,但这太慢了。列表通常包含至少 2500 个 1-6 个单词长的句子。

就像一个注释,它不一定是列表。可能是 HashMaps 或其他任何东西。希望有人能指出我正确的方向。

【问题讨论】:

    标签: c#


    【解决方案1】:

    这是一种使用哈希集字典进行预处理的方法list2 - 总体而言是 O(n*m),n = 列表 1 中的单词数,m = 列表 2 中的句子数(不包括预处理):

    var list1 = new List<string>() { "free bar", "hello world", "foo" };
    var list2 = new List<string>() { "hello there world", "foobar", "bar" };
    var wordMap = new Dictionary<string, HashSet<int>>();
    
    for(int i = 0; i< list2.Count; i++)
    {
        var words = list2[i].Split(' ');
        foreach(var word in words)
        {
            if(!wordMap.ContainsKey(word))
            {
                wordMap[word] = new HashSet<int>();
            }
            wordMap[word].Add(i);
        }
    }
    
    foreach(var item in list1)
    {
        bool foundMatch = false;
        var words = item.Split(' ');
        for (int i = 0; i < list2.Count;i++ )
        {
            foundMatch = words.All(word => !wordMap.ContainsKey(word) ? false : wordMap[word].Contains(i));
            if(foundMatch)
            {
                Console.WriteLine("Found matching sentence in list 2: " + list2[i]);
            }
        }
    }
    

    实际上,这应该比任何字符串比较都要快。

    【讨论】:

    • 哇,这正是我需要的。非常感谢老兄!
    猜你喜欢
    • 1970-01-01
    • 2014-06-21
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    相关资源
    最近更新 更多