【问题标题】:Counting Word Frequency (most significant words) in a String, excluding keywords计算字符串中的词频(最重要的词),不包括关键字
【发布时间】:2011-04-06 04:26:49
【问题描述】:

我想计算一个字符串中单词(不包括某些关键字)的出现频率,然后对它们进行 DESC 排序。那么,我该怎么做呢?

在下面的字符串中...

This is stackoverflow. I repeat stackoverflow.

排除关键字在哪里

ExKeywords() ={"i","is"}

输出应该是这样的

stackoverflow  
repeat         
this           

附:不!我不是在重新设计谷歌! :)

【问题讨论】:

    标签: vb.net linq count word-count word-frequency


    【解决方案1】:
    string input = "This is stackoverflow. I repeat stackoverflow.";
    string[] keywords = new[] {"i", "is"};
    Regex regex = new Regex("\\w+");
    
    foreach (var group in regex.Matches(input)
        .OfType<Match>()
        .Select(c => c.Value.ToLowerInvariant())
        .Where(c => !keywords.Contains(c))
        .GroupBy(c => c)
        .OrderByDescending(c => c.Count())
        .ThenBy(c => c.Key))
    {
        Console.WriteLine(group.Key);
    }
    

    【讨论】:

    • 如果这是一个非常大的字符串(比如 12,000 个单词),Regex 仍然是正确的方法吗?
    • @discorax 试试看!要在单词边界上拆分大字符串,Regex 应该与简单的自定义实现一样高效。您可能会从自定义解析器中获得更好的性能,但我怀疑这是否值得。对于较大的输入长度 n,Linq 的性能可能是限制因素。但是我相信 Linq 已经得到了相当好的优化,所以我怀疑上面描述的生产量是 O(nk)。如果关键字的数量更大(例如>4),最好将它们放入字典中,使整体时间复杂度为 O(n)。
    【解决方案2】:
    string s = "This is stackoverflow. I repeat stackoverflow.";
    string[] notRequired = {"i", "is"};
    
    var myData =
        from word in s.Split().Reverse()
        where (notRequired.Contains(word.ToLower()) == false)
        group word by word into g
        select g.Key;
    
    foreach(string item in myData)
        Console.WriteLine(item);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      相关资源
      最近更新 更多