2009-10-26 141 views
0
class CounterDict<TKey> 
{ 
    public Dictionary<TKey, int> _dict = new Dictionary<TKey, int>(); 

    public void Add(TKey key) 
    { 
     if(_dict.ContainsKey(key)) 
      _dict[key]++; 
     else 
     { 
      _dict.Add(key, 1); 
     } 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     string line = "The woods decay the woods decay and fall."; 

     CounterDict<string> freq = new CounterDict<string>(); 
     foreach (string item in line.Split()) 
     { 
      freq.Add(item.Trim().ToLower()); 
     } 

     foreach (string key in freq._dict.Keys) 
     { 
      Console.WriteLine("{0}:{1}",key,freq._dict[key]); 
     }   
    } 
} 

我想计算一个字符串中所有单词的出现次数。
我觉得上面的代码将是缓慢的,在这个任务,因为(考虑添加功能):如何计算文本文档中所有单词的频率?

if(_dict.ContainsKey(key)) 
    _dict[key]++; 
    else 
    { 
     _dict.Add(key, 1); 
    } 

而且,保持_dict__public好的做法呢? (我不认为是这样。)

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

回答

4

如何:

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]++; 
    } 
} 

主要点是用正则表达式替换.Split,所以你并不需要保存在内存中一个很大的字符串数组,你可以在时间和精力做一件事情。

+0

但是,“非字符串”键呢?我计划将此扩展到其他关键类型。 – 2009-10-26 12:08:19

+0

“或者还有非字符串的REGEX? :) – 2009-10-26 12:08:50

+0

你是什么意思'非字符串'? '\ w +'表示'[a-zA-Z_0-9]'(或'从A到Z的字母,下划线和数字') – 2009-10-26 12:17:58

2

从MSDN文档:

// 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."); 
    } 

没有测试它自己,但它可能会提高您的工作效率。

相关问题