• 作业三:词频统计


    词频统计

    要求:

    实现一个控制台程序,给定一段英文字符串,统计其中各个英文单词(4字符以上含4字符)的出现频率。输出要求:按照频率降序输出单词及频率,相同频率则按字母顺序输出。 

    源程序:

    #include <iostream>  
    #include <string>  
    using namespace std;  
     
     struct Word  
     {
         string Str;  
         int Count;   
     };  
     
     void CalcCount(Word *words,string &newWord,int size)  //统计词频
     {  
         int i=0;  
         for(;i<size;i++)  
         {  
            if(words[i].Str==newWord)  
             {  
                 words[i].Count++;  
                 return;  
             }  
             else if(words[i].Str=="")  
                 break;  
         }  
        words[i].Str=newWord;  
        words[i].Count =1;  
     }  
    
     int main()  
     {
         Word *words;  
         string content;  
         cout<<"输入一段英文:";  
         getline(cin, content);    //从输入流读入指定字符串
       
         int wCount = 1;  
         for(unsigned int i=0; i<content.length();i++)    //计算单词总数  
         {  
             if(content[i]==' ')  
                 wCount++;  
         }  
    
         words=new Word[wCount];  
       
         string::size_type offset=content.find(' ');//单词都是以空格隔开  
         while(offset!=string::npos)  
         {  
             string wStr=content.substr(0,offset);   //string.substr()从0开始返回长度为offset的字符串
            if (wStr.length()<4)                //除去长度小于4的单词
            {
                wCount--;
                content.erase(0,offset+1);
                offset=content.find(' ');
                continue;
            }
         
             content.erase(0,offset+1);             //string.erase()删除从0开始的长度为offset+1的字符串
             CalcCount(words,wStr,wCount);  
             offset=content.find(' ');   
         }
        
        if (content.length()>= 4)
        {
            CalcCount(words, content, wCount);                           //计算最后一个单词 
        }
        else wCount--;
    
        for (int j=0; j<wCount; j++)
        {
            if (words[j].Str=="")
            {
                wCount--;
            }
        }
       
    
         for(i=0;i<wCount-1;i++)  
         {  
             cout << words[i].Str << "频率:" << words[i].Count << "" << endl;  
         }  
        
         delete [] words;  
         return 0;  
     } 

    预估时间:

    词频统计:3小时  实际:5小时

    查找字符:2小时  实际:2小时

    实验结果:

    程序的思路:

    先设计一个统计词频的函数,而后读入输入的字符串,读入长度大于4的单词,以空格分离,删除长度小于4的单词。

    遇到的问题与总结:

    没能将大写字母改成小写字母,输入的字符串中也不能存在逗号。这次程序很难,跟室友讨论了很久,还是没能写出符合要求的程序。最后的结果也还是有错误。这次的作业我还是不会,希望老师下次出题目可以简单一点。

    附上github链接:https://github.com/skyhiahiahia/homework3

  • 相关阅读:
    jdk安装
    ubuntu 搜狗输入法成功安装
    matlab load
    matlab save 命令
    数字信号处理的思考
    非最大值抑制nms
    HMM,MEMM,CRF模型
    [bzoj2301][HAOI2011]Problem b
    [洛谷P3935]Calculating
    [bzoj4816][Sdoi2017]数字表格
  • 原文地址:https://www.cnblogs.com/sunkaiyue/p/5284670.html
Copyright © 2020-2023  润新知