码迷,mamicode.com
首页 > 其他好文 > 详细

第二次作业

时间:2017-09-16 14:51:47      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:span   blog   sort   大小写   重叠   lin   第二次作业   文件中   col   

  本次作业采用c#语言进行编程。主要功能包括:

  1)在指定文件中进行输入,之后运行程序进行词频统计。

  2)输入文件夹中的文件名,并对其进行词频统计

  3)对指定目录遍历其中文件,对每一个文件进行词频统计,并输出前10个出现率最高的单词

  4)在控制台输入文本内容,并统计它的词频。

  各个功能调用的主要函数都有很大部分的重叠,如都调用了CountEachWord方法,对此主要函数进行说明:

   1. CountEachWord(string url,int choice)划分文件中的单词,在这个程序中凡是一字母开头的文本算是一个单词,如1a不算是单词,但是a1算是一个单词。程序中使用了正则表达式进行匹配单词项,使用regex中的Matches方法得到一个单词Match集合,并将其存储到忽略大小写的hashtable中。

            int count = 0;  //单词总数统计变量
            StreamReader streamReader = new StreamReader(url);
            string line;
            Regex regex = new Regex(@"\b[A-Za-z]+[A-Za-z0-9]*");
            while ((line = streamReader.ReadLine()) != null)
            {

                MatchCollection matchCollection = regex.Matches(line);
                foreach(Match word in matchCollection)
                {
                    string words = word.ToString();
                    if (hashtable.Contains(words))
                    {
                        int j = Convert.ToInt32(hashtable[words]) + 1;
                        hashtable[words] = j;
                    }
                    else
                    {
                        hashtable.Add(words, 1);
                    }
                }
            }
            //输出文章中不重复的单词总数
            count = hashtable.Keys.Count;
            Console.WriteLine("total: " + count);

  2. 对hash表中的单词数从大到小进行排序。先将hashtable中的键(单词)和值(单词频率)存储到数组,以数组索引值为链接。使用了快速排序。快速排序的时间复杂度为O(nlogn)

            ArrayList arrayList = new ArrayList(hashtable.Keys);
            string[] keyArray = new string[arrayList.Count];
            int[] valueArray = new int[arrayList.Count];
            int index = 0;
            foreach(string key in arrayList)
            {
                //keyArray[index] = key;
                keyArray[index] = Convert.ToString(key);
                valueArray[index] = Convert.ToInt32(hashtable[key]);
                index++;
            }
            //快速排序递归算法
            QuickSort(valueArray,keyArray, 0, arrayList.Count - 1);

 

第二次作业

标签:span   blog   sort   大小写   重叠   lin   第二次作业   文件中   col   

原文地址:http://www.cnblogs.com/clairewyd/p/7531028.html

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