標籤: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 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>統計文本中的單詞