C++流操作练习:统计一篇英文(The_Holy_Bible.txt)文章中出现的单词和词频 并组成字典

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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值