从List <string []>到字典中获取唯一字符串的计数

ccs*_*csv 3 c# arrays dictionary

我想输入List<string[]>

输出是一个字典,其中的键是用于索引的唯一字符串,其值是一个浮点数数组,该数组中的每个位置都代表a string[]中键的计数List<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();

    }
Run Code Online (Sandbox Code Playgroud)

我卡在字典部分。最有效的方法是什么?

Jon*_*eet 5

听起来您可以使用类似:

var dictionary = doc
    .SelectMany(array => array)
    .Distinct()
    .ToDictionary(word => word,
                  word => doc.Select(array => array.Count(x => x == word))
                             .ToArray());
Run Code Online (Sandbox Code Playgroud)

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

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

请注意,这创造了一个Dictionary<string, int[]>,而不是一个Dictionary<string, float[]>-它似乎更明智的给我,但你总是可以投的结果Countfloat,如果你真的想。