【问题标题】:Word frequency with static IEnumerable<KeyValuePair<string, int>>静态 IEnumerable<KeyValuePair<string, int>> 的词频
【发布时间】:2016-12-07 16:21:49
【问题描述】:

你好,

我写了这个函数来计算一个完整的单词列表中的元音。

static IEnumerable<KeyValuePair<char, int>> Sthmpa(string sourceItem)
{
     return sourceItem.ToLower()
                .Where(c => "aeiou".Contains(c))
                .GroupBy(c => c, (c, instances) => new KeyValuePair<char, int>(c, instances.Count()));
}

我想更改此返回以计算列表中的单词频率。

这是一个充满单词的列表。

static IList<string> lines = new List<string>();

像这样:

var g = lines.GroupBy(words=> words);
foreach (var grp in g)
{
     Console.WriteLine("{0} {1}", grp.Key, grp.Count());
}

我打印了词频,但我想让这个像我计算元音一样。

谁能告诉我如何改变?

要清楚,我在线程函数中使用的函数SthmpaConcurrentBag...

【问题讨论】:

  • lines 可以有多少个单词?因为您似乎试图解决此问题的方式可能会出现非常严重的性能问题。
  • 我不知道程序中有多少个单词,因为我是从一些文件中获取它们的。也许我可以数一数,但是……
  • 每行是一个词还是每行可以有多个词?
  • 每行可以有多个单词
  • 您可能希望在返回数据之前在其中抛出一个.ToList(),每次评估返回的IEnumerable&lt;KeyValuePair&lt;char, int&gt;&gt; 时,它都会重新运行WhereGroupBy,通过放置在返回结果之前将其发送到ToList(),它将在重复使用期间使用缓存的结果。

标签: c# multithreading linq dictionary


【解决方案1】:

你可以试试这个:

public IEnumerable<KeyValuePair<string, int>> GetWordFrequency(List<string> words)
{
    return words.GroupBy(w => w)
                .Select((item) => new KeyValuePair<string, int>(item.Key, item.Count()));
}

【讨论】:

  • 谢谢!我想这很好用,但我在另一个函数中使用了这个函数,现在我收到“无法从使用中推断”的错误......无论如何,谢谢!
  • Error 1 The type arguments for method 'ConsoleApplication1.Program.DoingAll&lt;TSource,TKey,TValue,TResult&gt;(System.Collections.Generic.IEnumerable&lt;TSource&gt;, System.Func&lt;TSource,System.Collections.Generic.IEnumerable&lt;System.Collections.Generic.KeyValuePair&lt;TKey,TValue&gt;&gt;&gt;, System.Func&lt;System.Collections.Generic.KeyValuePair&lt;TKey,System.Collections.Generic.IEnumerable&lt;TValue&gt;&gt;,TResult&gt;)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
  • 可能问题出在方法 DoingAll 的第三个参数上。第二个参数与您的方法 Sthmpa 匹配。但是第三个参数与以 KeyValuePair 作为参数的方法匹配。这就是你想要的吗?
  • 我会尝试发布第二个函数
【解决方案2】:

这是我的方法:

private IEnumerable<KeyValuePair<string, int>> GetOccurences(IEnumerable<string> words)
{
    return words.GroupBy(word => word, StringComparer.InvariantCultureIgnoreCase)
                .Select(group => new KeyValuePair<string, int>(group.Key, group.Count()))
                .OrderByDescending(kvp => kvp.Value);
}

【讨论】:

    猜你喜欢
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多