分析英文文本各个词出现的频率

      软件工程 (Software Engineering,简称为SE)是一门研究用工程化方法构建和维护有效的、实用的和高质量的软件的学科。在软件工程课上,老师布置了一个任务:

分析英文文本各个词出现的频率,取前十输出。

  这个题目一拿到手,首先,是学习以前的知识来编写程序,知识点有I/O流的输入输出,排序,还有一些小语法。

代码如下:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

//定义存储单词和出现次数的结构体
typedef struct{
string word;
int num;
}count;

int main()
{int x;
vector<count> v;
count tempstr;
tempstr.num=0;
ifstream in("english.txt");
string temp;
string str;
int count=0;
int j=0;

//按行读取文件,对每行信息截取单词并计数
while(getline(in,temp))
{
for(int i=0;i<temp.length ();i++)
{
if((temp[i]>='a'&&temp[i]<='z')||(temp[i]>='A'&&temp[i]<='Z'))
count++;
else if(count)
{
str=temp.substr (i-count,count);
if(v.size ())
{
for(j=0;j<v.size ();j++)
if(str.compare(v[j].word )==0)
{
v[j].num ++;
count=0;
break;
}
} //end if
if(j>=v.size ())
{
tempstr.word = str;
tempstr.num =1;
v.push_back (tempstr);
count = 0;
}
}
}
}
for(int m=10;m>1;m--)
for(int i=0;i<v.size();i++)
{if(v[i].num<v[i+1].num)
{
x=v[i].num;
v[i].num=v[i+1].num;
v[i+1].num=x;
}

cout<<""<<v[i].word<<" "<<v[i].num<<endl;}
return 0;
}

最后得到的结果好像还有点问题,正在继续排查当中。

时间列表:

 3月1日 3个小时

 3月2日 4个小时

 3月3日 2个小时

 3月4日 1个小时。。。

原文地址:https://www.cnblogs.com/zhouyahao/p/3580583.html