作业3 个人项目—词频统计

1. 目标

  • 使用开发工具 Visual C++
  • 开发语言 C++
  • 使用源代码管理工具(Github)

2. 要求

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

 

3.实验结果

源代码如下:

#include <iostream> 
#include <string>   
using namespace std; 
 
struct Word 

    Word() : Str(""), Count(0) {} 
    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)  // 统计词频,words单词数组,newWord 单词内容,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)  //以单词出现频率降序排列单词,words 单词数组,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); 
 
 extern char *strlwr(string content);
    int wCount = 1;      //计算单词总数
    for(int k=0; k<content.length(); k++) 
    { 
        if(content[k] == ' ') 
            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); 
 
    for(int i = 0; i <wCount; i++) 
    { 
        cout << words[i].Str <<"频率:" << words[i].Count << "次" << endl; 
    } 
 
    delete [] words; 
    return 0; 

 

结果如下:

 

 

 

4.实验感想

我花了半天的时间来写这个程序,虽然运行出了程序也能完成统计,但是仍旧有几个地方未能满足题目要求,我使用了string中的strlwr来进行大写转小写,但不知怎么回事仍然没有实现,还有输入的代码的单词之间只能以单一的非字母数字隔开(我用的‘ ’),换了其他的就无法识别了,这个问题我思考了很久都没有找到解决方案,我也想过设定范围,但是那样步骤繁多不算精炼。

如果区分大小写且单词之间以空格隔开,这个程序就能完成统计。

posted on 2016-03-16 18:04  叶月欣  阅读(247)  评论(0编辑  收藏  举报