xiacy

导航

3.2.1 泛型例子,泛型字典统计文本中的单词数

        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[] args)
        {
            string text = @"ay,iyaiyai
                            ay,iyaiyai
                            ay,iyaiyai
                            where's my samural?
                            i've been searching for a man
                            allacross japan
                            just to find,to find my samural
                            someone who is strong
                            but still a little shy
                            yes i need,i need my samural
                            ay,ay,ay
                            i'm your little butterfly
                            green,black and blue
                            make the colours of the sky
                            ay,ay,ay
                            i'm your little butterfly
                            green,black and blue
                            make the colours of the sky
                            i've been searching in the woods
                            and high upon the hills
                            just to find,to find my samural
                            someone who won't regret
                            to keep me his net
                            yes i need,i need my samural";
            Dictionary<string, int> freque = CountWords(text);
            foreach (KeyValuePair<string, int> entry in freque)
            {
                string word = entry.Key;
                int freques = entry.Value;
                Console.WriteLine("{0}:{1}", word, freques);
            }
        }

 

posted on 2012-05-01 10:53  xiacy  阅读(312)  评论(0编辑  收藏  举报