2015-07-10 23 views
3

我想输入一个List<string[]>获取从一个列表<string[]>唯一的字符串的计数到字典

输出是一个字典,其中键是用于一个索引和值唯一的字符串是float数组在阵列中表示关键的一个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(); 

    } 

我被困在字典中的一部分。什么是最有效的实施方式?

+0

为什么你会在这里使用'float'?什么将会是一个非整数值? –

+1

您能否提供预期产出的样本? – dcastro

+0

理想情况下有一个更有用的输入,其中有不止一次出现单词... –

回答

4

这听起来像你可以使用类似:

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<string, int[]>,而不是一个Dictionary<string, float[]> - 它似乎更明智的给我,但你总是可以的Count结果转换为float如果你真的想。

相关问题