码迷,mamicode.com
首页 > Windows程序 > 详细

《深入理解C#》代码片段-用Dictionary<TKey,TValue>统计文本中的单词

时间:2014-12-16 22:35:11      阅读:556      评论:0      收藏:0      [点我收藏+]

标签:style   blog   ar   io   color   sp   for   on   div   

 1     public class Words
 2     {
 3         public static Dictionary<string, int> CountWords(string text)
 4         {
 5             Dictionary<string, int> frequencies;//创建从单词到频率的新映射
 6             frequencies = new Dictionary<string, int>();
 7             string[] words = Regex.Split(text, @"\W+");//将文本分解成单词
 8             //添加或跟新映射
 9             foreach (var word in words)
10             {
11                 if (frequencies.ContainsKey(word))
12                 {
13                     frequencies[word]++;
14                 }
15                 else
16                 {
17                     frequencies[word] = 1;
18                 }
19             }
20             return frequencies;
21         }
22     }

打印

 1   static void Main(string[] args)
 2   {
 3       string text = "President Xi Jinping has asked the armed forces to clear up the bad influence left by the graft case of Xu Caihou, a former senior commander.";
 4       Dictionary<string, int> frequencies = Words.CountWords(text);
 5       foreach (KeyValuePair<string,int> entry in frequencies)
 6       {
 7           string word = entry.Key;
 8           int frequency = entry.Value;
 9           Console.WriteLine("{0}:{1}", word, frequency);
10       }
11       Console.ReadKey();
12   }

 

《深入理解C#》代码片段-用Dictionary<TKey,TValue>统计文本中的单词

标签:style   blog   ar   io   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/Ares945/p/Dictionary.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!