习题:统计文章的词频
-
统计一篇英文(The_Holy_Bible.txt)文章中出现的单词和词频,
输入:某篇文章的绝对路径
输出:词典(词典中的内容为每一行都是一个“单词 词频”词典的存储格式如下
| a 66 |
| abandon 77 |
| public 88 |
| … |
|_________________|
struct Word
{
string _word;
int _fre;
};
vector<Word>
class Dictionary
{
public:
//......
void read(const std::string & filename);
void store(const std::string & filename);
private:
//......
};
解题思路:
- 有结构体Word,包含单词_word 与 词频 _fre
- Dictionary类中需要有vector容器,储存word数据(每个单词与词频的结构体)
- Dictionary类中有读取文件的函数、储存到文件的函数
- 读取文件的函数先读一行(getline函数),然后在这一行的字符串中读取一个单词 (字符串输输入流得到一行,一个一个的读)
- 读取单词的时,简单的判断单词是否合理(例如:aband34n 中间夹杂字母,为不合理单词)
- 如果单词合理时,循环vector容器,判断单词是否与当前Word中的_word是否相等,相等则这个单词的词频加一,不相等则把当前的Word结构体push_back到vector容器的最后
- 最好在vector容器中按单词的字母顺序排好序 (sort函数,需要重载<运算符)
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using std::cout;
using std::cin;
using std::endl;
using std::cerr;
using std::string;
using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::vector;
using std::sort;
//record是单词和词频的结构体
struct record
{
//构造函数,初始化_word和_frequency
record(const string &word, int frequency)
:_word(word)
,_frequency(frequency)
{
}
string _word;
int _frequency;
};
//重载运算符< 用于sort函数中的排序
bool operator<(const record &lhs, const record &rhs)
{
return lhs._word < rhs._word;
}
//类
class dictionary
{
public:
//构造函数
dictionary()
{
}
//读取文件中的单词与词频
void read(const string &filename)
{
ifstream ifs(filename);
if(!ifs)
{
cerr << "ifs open file" << filename << "error!" << endl;
return;
}
string line;
//读取一行
while(getline(ifs, line))
{
//字符串输入流接收文本中一行的内容
istringstream iss(line);
string word;
//字符串输入流输出以空格为分割符
while(iss >> word) //word可能是不规范的单词abc123
{
string newword = dealword(word); // newword是处理后的单词
insert(newword); // 把处理后的单词插入到vector中
}
}
sort(_dict.begin(), _dict.end());
ifs.close();
}
//把单词与词频存储到文件中
void store(const string &filename)
{
ofstream ofs(filename);
if(!ofs)
{
cerr << "ofs open" << filename << "error!" << endl;
return;
}
for(size_t idx = 0; idx != _dict.size(); ++idx)
{
ofs << _dict[idx]._word << " " << _dict[idx]._frequency << endl;
}
ofs.close();
}
//对不符合要求的单词进行处理
string dealword(const string &word)
{
size_t idx = 0;
for(;idx != word.size(); ++idx)
{
if(!isalpha(word[idx]))
{
return string();
}
}
return word;
}
//把结果插入到vector中
void insert(const string &word)
{
if(word == string())
{
return;
}
size_t idx =0;
for(; idx != _dict.size(); ++idx)
{
if(word == _dict[idx]._word)
{
++_dict[idx]._frequency;
break;
}
}
if(idx == _dict.size())
{
_dict.push_back(record(word, 1));
}
}
private:
vector<record> _dict;
};
int main()
{
dictionary dict;
cout << "begin reading... " << endl;
time_t beg = time(NULL);
dict.read("The_Holy_Bible.txt");
time_t end = time(NULL);
cout << "time : " << (end-beg) << "s" << endl;
cout << "after reading!" << endl;
dict.store("sult.txt");
return 0;
}