基于C++的字符统计程序

题目:
写一个程序,分析一个一个文本文件中各个词出现的频率,并且把频率最高的10个词打印出来。文本文件大约是30KB~300KB大小。
开发语言:C++
开发环境:VS2012
文本文件:test.txt-31.9KB;test1.txt-326KB

计划:
1.开发周期:1周
2.需求分析:统计单词出现次数并记录
3.概要设计:由于每个单词间存在空格,可以以空格为依据进行统计。运用C++向量方法较为方便。
工程下载
程序源代码:
#pragma warning(disable:4996)
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;


int cmp(const pair &a, const pair &b){
return a.second > b.second;
}
int main(){
double t=clock();
freopen("test.txt", "r", stdin);
map mp;
string word = "";
char tmp;
while ((tmp = getchar()) != EOF){
if (tmp >= 0 && tmp <= 255){
if (!isalpha(tmp)){
if (word != ""){
mp[word]++;
}
word = "";
}
else {
word += tmp;
}
}
}
vector > v;
for (map::iterator it = mp.begin(); it != mp.end(); ++it){
v.push_back(*it);
}
sort(v.begin(), v.end(), cmp);
int cct = 0;
cout << "出现次数前十的单词是: "  << endl;
for (int i = 0; i < v.size(); i++){
cout.setf(ios::left);
cout.width(2);
cout<
cout<<"、";
cout.width(12);
cout << v[i].first;
cout<< " 出现次数: "<< v[i].second <
if (cct++ > 10){
break;
}
}
cout<<"程序用时:"<<(clock()-t)/CLOCKS_PER_SEC<<"s"<< endl; 
}

程序效果:
test.txt结果:
基于C++的字符统计程序
test1.txt结果:
基于C++的字符统计程序

Analyze:
基于C++的字符统计程序

基于C++的字符统计程序


基于C++的字符统计程序

基于C++的字符统计程序

总结与反思:

本程序基本实现了所需功能,但仍有可改进地方。如大小写的一致性问题以及虚词过滤问题。经过本次软件小项目的学习,我初步掌握了一个软件开发的基本流程及方法,为今后发展打下基础。

你可能感兴趣的:(编程学习)