[英]Getting a count of unique strings from a List<string[]> into a dictionary
我想輸入一個List<string[]>
和
輸出是一個字典,其中鍵是用於一個索引唯一的字符串以及值是浮點數的數組與陣列中表示密鑰的計數為每一個位置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();
}
我被困在字典部分。 實現這一目標的最有效方法是什么?
聽起來你可以使用類似的東西:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.