计算每个单词的频率

3 .net c# .net-4.0 c#-4.0 word-frequency

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

aKz*_*enT 10

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

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

您可以像这样调用此代码:

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

        countWordsInFile("file1.txt", words);
Run Code Online (Sandbox Code Playgroud)

在此之后的话将包含文件中的所有单词,它们的频率(例如words["test"]返回的次数是"测试"是在文件的内容.如果你需要从多个文件累积的结果,简单地调用所有文件的方法如果你需要为每个文件单独的结果,那么每次都要创建一个新的字典并使用像@DarkGray建议的结构.