作业三-----词频统计

时间:2022-01-03 21:56:51

准备阶段:

开发工具:VC6.0

所用语言:c++

预计完成程序需要:好长时间

实际完成时间:12h

要求:

实现一个控制台程序,给定一段英文字符串,统计其中各个英文单词(4字符以上含4字符)的出现频率。 附加要求:读入一段文本文件,统计该文本文件中单词的频率。

 

作业三-----词频统计

思路:

分成三个模块,查找,排序,计算。

 

#include <iostream>  
#include <string>//字符串  
using namespace std;  
 
 struct Word //结构体定义 
 {  string Str;  
    int Count;  

     void exchange(Word &word)  
    {   string tStr = word.Str;  
        int tCount = word.Count;  
        word.Str = Str;  
        word.Count = Count;  
        Str = tStr;  
        Count = tCount; }  
 };  
 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;  
 }  
 void SortWordDown(Word * words, int size)  
 {  
     for(int i = 0; i < size; i++)  
     {  
         for(int j = 0; j < size-1; j++)  
         {  
             if(words[j].Count <  words[j+1].Count)  
             {  words[j].exchange(words[j+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);  
         content.erase(0, offset+1);  
         CalcCount(words, wStr, wCount);  
         offset = content.find(' ');  
     }  
     CalcCount(words, content, wCount);//计算最后一个单词  
   
     SortWordDown(words, wCount);  
     int printCount = wCount < 5 ? wCount : 5;  
     cout << "单词分别出现的频率:" << endl;  
     for(i = 0; i < printCount; i++)  
     {  
         cout << words[i].Str << "出现的频率:" << words[i].Count << "" << endl;  
     }  
    作业三-----词频统计

总结:

我觉得这次作业对于我来说很难,和舍友讨论也没有什么实质性的进展,然后就在求助百度了,但是并没有达到全部的要求。根据网上大神的程序,自己敲出来的错误太多。刚开始看到这个题目的时候,我是一头雾水,不知道从哪里入手。但是最后的程序还是没能达到全部要求。程序不能读入文本文档,对其中的内容进行统计。其实这个。。。

 我的github链接:https://github.com/MocQiQi/homework