【问题标题】:To count the frequency of each word计算每个单词的频率
【发布时间】:2023-03-22 19:51:01
【问题描述】:

有一个包含一些文本文件的目录。如何计算每个文件中每个单词的频率?单词是指一组字符,可以包含字母、数字和下划线字符。

【问题讨论】:

  • 你想做什么?你是如何尝试的?怎么没用?
  • 我不知道我应该先做什么。主要问题是如何搜索单词?我应该使用什么通用容器来存储有关单词、计数频率和文件的信息。

标签: c# .net c#-4.0 .net-4.0 word-frequency


【解决方案1】:

这是一个计算文件中所有词频的解决方案:

    private void countWordsInFile(string file, Dictionary<string, int> words)
    {
        var content = File.ReadAllText(file);

        var wordPattern = new Regex(@"\w+");

        foreach (Match match in wordPattern.Matches(content))
        {
            int currentCount=0;
            words.TryGetValue(match.Value, out currentCount);

            currentCount++;
            words[match.Value] = currentCount;
        }
    }

你可以这样调用这段代码:

        var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);

        countWordsInFile("file1.txt", words);

在此之后的单词将包含文件中的所有单词及其频率(例如words["test"] 返回“test”在文件内容中的次数。如果您需要从多个文件中累积结果,只需为具有相同字典的所有文件调用该方法。如果您需要为每个文件提供单独的结果,则每次创建一个新字典并使用@DarkGray 建议的结构。

【讨论】:

    【解决方案2】:

    有一个 imo 更简单的 Linq-ish 替代方案。这里的关键是使用File.ReadLines(懒人阅读很酷)和string.Split内置的框架。

    private Dictionary<string, int> GetWordFrequency(string file)
    {
        return File.ReadLines(file)
                   .SelectMany(x => x.Split())
                   .Where(x => x != string.Empty)
                   .GroupBy(x => x)
                   .ToDictionary(x => x.Key, x => x.Count());
    }
    

    要从多个文件中获取频率,您可以基于params 进行重载。

    private Dictionary<string, int> GetWordFrequency(params string[] files)
    {
        return files.SelectMany(x => File.ReadLines(x))
                    .SelectMany(x => x.Split())
                    .Where(x => x != string.Empty)
                    .GroupBy(x => x)
                    .ToDictionary(x => x.Key, x => x.Count());
    }
    

    【讨论】:

      【解决方案3】:

      字数统计:

      int WordCount(string text)
      {
        var regex = new System.Text.RegularExpressions.Regex(@"\w+");
      
        var matches = regex.Matches(text);
        return matches.Count;     
      }
      

      从文件中读取文本:

      string text = File.ReadAllText(filename);
      

      字数统计结构:

      class FileWordInfo
      {
        public Dictionary<string, int> WordCounts = new Dictionary<string, int>();
      }
      
      List<FileWordInfo> fileInfos = new List<FileWordInfo>();
      

      【讨论】:

      • 这个正则表达式是否允许一组只能包含字母、数字和下划线字符的字符?我应该使用哪个通用容器来存储有关单词、计数频率和文件的信息?
      • @Grienders 检查当前变体
      • 你的代码是做什么的?它不能满足我的需要!是统计每个单词的出现频率还是统计所有单词的数量?
      【解决方案4】:

      @aKzenT 答案很好,但是有问题!他的代码从不检查字典中是否已经存在该单词!所以我修改了代码如下:

      private void countWordsInFile(string file, Dictionary<string, int> words)
      {
          var content = File.ReadAllText(file);
      
          var wordPattern = new Regex(@"\w+");
      
          foreach (Match match in wordPattern.Matches(content))
          {
              if (!words.ContainsKey(match.Value))
                  words.Add(match.Value, 1);
              else
                  words[match.Value]++;
          }
      }
      

      【讨论】:

        【解决方案5】:
        string input= File.ReadAllText(filename);
        var arr = input.Split(' ');
        // finding frequencies of words in a string
        IDictionary<string, int> dict = new Dictionary<string, int>();
        foreach (var item in arr)
        {
            var count = 0;
            if (dict.TryGetValue(item, out count))
                dict[item] = ++a;
            else
                dict.Add(item, 1);
        }
        

        【讨论】:

        • 继续向这段代码发送文件名以查找每个文件的频率。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-27
        • 1970-01-01
        • 1970-01-01
        • 2014-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多