【问题标题】:Getting a count of unique strings from a List<string[]> into a dictionary将 List<string[]> 中的唯一字符串计数到字典中
【发布时间】:2015-09-29 01:10:09
【问题描述】:

我想输入List&lt;string[]&gt;

输出是一个字典,其中键是用于索引的唯一字符串,值是浮点数组,数组中的每个位置表示List&lt;string[]&gt;string[] 的键计数

到目前为止,这是我尝试过的

static class CT
{
    //Counts all terms in array
    public static Dictionary<string, float[]> Termfreq(List<string[]> text)
    {
        List<string> unique = new List<string>();

        foreach (string[] s in text)
        {
            List<string> groups = s.Distinct().ToList();
            unique.AddRange(groups);
        }

        string[] index = unique.Distinct().ToArray();

        Dictionary<string, float[]> countset = new Dictionary<string, float[]>();


         return countset;
    }

}



 static void Main()
    {
        /* local variable definition */


        List<string[]> doc = new List<string[]>();
        string[] a = { "That", "is", "a", "cat" };
        string[] b = { "That", "bat", "flew","over","the", "cat" };
        doc.Add(a);
        doc.Add(b);

       // Console.WriteLine(doc);


        Dictionary<string, float[]> ret = CT.Termfreq(doc);

        foreach (KeyValuePair<string, float[]> kvp in ret)
        {
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);

        }


        Console.ReadLine();

    }

我在字典部分卡住了。实现这一点的最有效方法是什么?

【问题讨论】:

  • 为什么要在这里使用float?什么是非整数值?
  • 您能否提供预期输出的样本?
  • 最好有一个更有用的输入,其中单词出现不止一次...
  • @JonSkeet 如果我想做任何数学运算 float 允许小数。
  • 但是计数永远不会是整数以外的任何东西。如果你想将它转换为一个数组,而不是一个计数,为了清楚起见,我会亲自创建一个新数组。

标签: c# arrays dictionary


【解决方案1】:

听起来你可以使用类似的东西:

var dictionary = doc
    .SelectMany(array => array)
    .Distinct()
    .ToDictionary(word => word,
                  word => doc.Select(array => array.Count(x => x == word))
                             .ToArray());

换句话说,首先找到一组不同的单词,然后为每个单词创建一个映射。

要创建映射,请查看原始文档中的每个数组,并找出该数组中单词出现的次数。 (所以每个数组都映射到一个int。)使用LINQ 对整个文档执行该映射,ToArray 为特定单词创建一个int[]……这就是该单词字典条目的值。

请注意,这会创建一个Dictionary&lt;string, int[]&gt; 而不是Dictionary&lt;string, float[]&gt; - 这对我来说似乎更明智,但如果你真的,你总是可以将Count 的结果转换为float想要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多