C# 从列表中获取唯一字符串的计数<;字符串[]>;查字典
我想输入一个C# 从列表中获取唯一字符串的计数<;字符串[]>;查字典,c#,arrays,dictionary,C#,Arrays,Dictionary,我想输入一个列表和 输出是一个字典,其中键是用于索引的唯一字符串,值是一个浮点数组,数组中的每个位置表示列表中字符串[]的键计数 到目前为止,这就是我所尝试的 static class CT { //Counts all terms in array public static Dictionary<string, float[]> Termfreq(List<string[]> text) { 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();
}
静态类CT
{
//计算数组中的所有项
公共静态词典Termfreq(列表文本)
{
List unique=新列表();
foreach(文本中的字符串[]s)
{
列表组=s.Distinct().ToList();
唯一。添加范围(组);
}
string[]index=unique.Distinct().ToArray();
字典计数集=新字典();
返回计数集;
}
}
静态void Main()
{
/*局部变量定义*/
列表单据=新列表();
字符串[]a={“That”,“is”,“a”,“cat”};
string[]b={“That”,“bat”,“fleed”,“over”,“the”,“cat”};
文件增补(a);
文件增补(b);
//控制台写入线(doc);
字典ret=CT.Termfreq(doc);
foreach(ret中的KeyValuePair kvp)
{
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[]
。。。这是该单词字典条目的值
请注意,这会创建一个字典而不是字典
——这对我来说似乎更合理,但如果您真的愿意,您可以将计数
的结果强制转换为浮动
。为什么在这里使用浮动
?什么是非整数值?你能提供一个预期输出的样本吗?理想情况下,如果有一个更有用的输入,其中有多次出现的单词…@JonSkeet如果我想做任何数学运算,float允许小数。但计数永远不会是整数以外的任何东西。如果你想把它转换成一个数组,而不是一个计数,为了清晰起见,我个人会在那个时候创建一个新数组。