标签: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