- class DictionaryDemo
- {
- static Dictionary<string,int> CountWords(string text)
- {
- Dictionary<string,int> frequencies;
- frequencies = new Dictionary<string,int>();
-
- string[] words = Regex.Split(text, @"\W+");
-
- foreach (string word in words)
- {
- if (frequencies.ContainsKey(word))
- {
- frequencies[word]++;
- }
- else
- {
- frequencies[word] = 1;
- }
- }
- return frequencies;
- }
-
- static void Main()
- {
- string text = @"Do you like green eggs and ham?
- I do not like them, Sam-I-am.
- I do not like green eggs and ham.";
-
- Dictionary<string, int> frequencies = CountWords(text);
- foreach (KeyValuePair<string, int> entry in frequencies)
- {
- string word = entry.Key;
- int frequency = entry.Value;
- Console.WriteLine("{0}: {1}", word, frequency);
- }
- }
- }
标题不支持<> 用Dictionary<TKey,TValule>来统计文本中的单词数
- Dictionary<string,int> frequencies;
创建从单词到频率的新映射, CountWords方法 创建 从string到int的空白映射,将统计每个单词在一段给定文本中的频率
- string[] words = Regex.Split(text, @"\W+");
将文本分解成单词,用正则表达式分解单词 但最终会得到两个空字符串 文本头尾各一个,没有去管 Do 和 do 分开计数的问题
- if (frequencies.ContainsKey(word))
- {
- frequencies[word]++;
- }
- else
- {
- frequencies[word] = 1;
- }
添加或者更新映射 对每个单词都检查它是否已经在映射中。 如果是,就增加现有计数,否则,就为单词赋予一个初始计数1 负责递增的代码不需要执行到 int的强制类型 转换,就可以执行加法运算:取回的值在编译时是int类型。
- foreach (KeyValuePair<string, int> entry in frequencies)
- {
- string word = entry.Key;
- int frequency = entry.Value;
- Console.WriteLine("{0}: {1}", word, frequency);
- }
打印映射中的每个键/值对 遍历一个Hashtable , Hashtable包含类似的DictionaryEntry, 其中每个条目都具有Key和Value属性 在c#1中,word和frequency都需要强制类型转换,因为Key和Value都返回 object类型, frequency还需要装箱 可以直接用entry.Key entry.Value, 因为是为了证明可以不用强制类型转换。
输入 - string text = @"Do you like green eggs and ham?
- I do not like them, Sam-I-am.
- I do not like green eggs and ham.";
输出 Do: 1 you: 1 like: 3 green: 2 eggs: 2 and: 2 ham: 2 I: 3 do: 2 not: 2 them: 1 Sam: 1 am: 1 : 1
|