C++流操作练习:统计一篇英文(The_Holy_Bible.txt)文章中出现的单词和词频 并组成字典
一.题目
统计一篇英文(The_Holy_Bible.txt)文章中出现的单词和词频,
输入:某篇文章的绝对路径
输出:词典(词典中的内容为每一行都是一个“单词 词频”)
词典的存储格式如下
| a 66 |
| abandon 77 |
| public 88 |
| … |
|_________________|
class Dictionary
{
public:
//......
void read(const std::string & filename);
void store(const std::string & filename);
private:
//......
};
二.代码
Dictionary.h
:
#ifndef _DICTIONARY_H_
#define _DICTIONARY_H_
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <fstream>
using std::ifstream;
using std::ofstream;
using std::pair;
using std::unordered_map;
using std::cout;
using std::endl;
using std::string;
using std::vector;
class Dictionary
{
public:
void read(const std::string &filename);
void store(const std::string &filename);
private:
unordered_map<string,int> _dict;
};
#endif
Dictionary.cpp
:
#include "Dictionary.h"
//读取filename文件
void Dictionary::read(const string& filename){
ifstream ifs(filename, ifstream::in);
if (!ifs){
cout << "ifs open Error!" << endl;
}
string word;
//一个单词一个单词读取
cout << "Start to read" << endl;
while (ifs.good()){
ifs >> word;
_dict[word]++;
}
cout << "Read Over" << endl;
ifs.close();
}
//将字典中的内容按照存储格式写到filename文件中
void Dictionary::store(const string& filename){
ofstream ofs(filename, ofstream::out);
vector<pair<string,int>> vec(_dict.begin(), _dict.end());
cout << "Start to write" << endl;
for (vector<pair<string,int>>::iterator it = vec.begin(); it != vec.end(); it++){
string key = it->first;
int value = it->second;
ofs << key << " " << value << endl;
}
cout << "write end" << endl;
ofs.close();
}
main.cpp
:
#include "Dictionary.h"
int main(){
string In = "The_Holy_Bible.txt";
string Out = "out.txt";
Dictionary dict;
dict.read(In);
dict.store(Out);
return 0;
}