C# 如何计算文本文档中所有单词的频率?

C# 如何计算文本文档中所有单词的频率?,c#,dictionary,C#,Dictionary,此外,是否保持良好的实践?(我认为不是。) 我应该如何修改或完全更改它来完成工作?这个怎么样: if(_dict.ContainsKey(key)) _dict[key]++; else { _dict.Add(key, 1); } 字典单词=新字典(); string input=“树木腐烂树木腐烂并倒下。”; foreach(Regex.Matches中的匹配字(输入@“\w+”,RegexOptions.ECMAScript)) {

此外,是否保持良好的实践?(我认为不是。)

我应该如何修改或完全更改它来完成工作?

这个怎么样:

    if(_dict.ContainsKey(key))
    _dict[key]++;
    else
    {
        _dict.Add(key, 1);
    }
字典单词=新字典();
string input=“树木腐烂树木腐烂并倒下。”;
foreach(Regex.Matches中的匹配字(输入@“\w+”,RegexOptions.ECMAScript))
{
如果(!words.ContainsKey(word.Value))
{
words.Add(word.Value,1);
}
其他的
{
字[字.值]+;
}
}

主要的一点是用正则表达式替换
.Split
,这样就不需要在内存中保留大字符串数组,一次可以处理一个项目。

来自msdn文档:

Dictionary<string, int> words = new Dictionary<string, int>();
string input = "The woods decay the woods decay and fall.";
foreach (Match word in Regex.Matches(input, @"\w+", RegexOptions.ECMAScript))
{
    if (!words.ContainsKey(word.Value))
    {
        words.Add(word.Value, 1);
    }
    else
    {
        words[word.Value]++;
    }
}

我自己还没有测试过,但它可能会提高您的效率。

是一些计算字符串发生次数的方法。

但是“非字符串”键呢。我还计划将其扩展到其他键类型。“或者也有用于非字符串的正则表达式?”:)你说的“非字符串”是什么意思?
\w+
表示
[a-zA-Z_0-9]
(或“从a到Z的字母、下划线和数字”)
Dictionary<string, int> words = new Dictionary<string, int>();
string input = "The woods decay the woods decay and fall.";
foreach (Match word in Regex.Matches(input, @"\w+", RegexOptions.ECMAScript))
{
    if (!words.ContainsKey(word.Value))
    {
        words.Add(word.Value, 1);
    }
    else
    {
        words[word.Value]++;
    }
}
    // When a program often has to try keys that turn out not to
    // be in the dictionary, TryGetValue can be a more efficient 
    // way to retrieve values.
    string value = "";
    if (openWith.TryGetValue("tif", out value))
    {
        Console.WriteLine("For key = \"tif\", value = {0}.", value);
    }
    else
    {
        Console.WriteLine("Key = \"tif\" is not found.");
    }