首页 > 代码库 > 《深入理解C#》代码片段-用Dictionary<TKey,TValue>统计文本中的单词
《深入理解C#》代码片段-用Dictionary<TKey,TValue>统计文本中的单词
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 else16 {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>统计文本中的单词
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。