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

标签 c# arrays dictionary

我想输入一个List<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();

    }

我卡在了字典部分。什么是最有效的实现方式?

最佳答案

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

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如果你真的想要。

关于c# - 从 List<string[]> 中获取唯一字符串的计数到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31338157/

相关文章:

无法让字符串搜索正常工作

python - 像类一样初始化字典

c# - 使用内联对象方法调用与声明新变量

c# - Xamarin-ios 共享和接收音频文件

php - 在mysql中添加相同行的值

java - Java 的数组 indexOf 在哪里?

python - 从字典列表中删除重复项会引发异常吗?

python - 查询集花费太多时间

c# - 使用 ServiceStack 的 Swagger UI 传递 header

c# - 无法在 C# 中使用 SSH.NET 上传文件 SFTP - 权限被拒绝