使用map重写词频统计。(之前使用的vector,可以比较他们的速率)

#include <iostream>
#include <map>
#include <string>
#include <fstream>
#include <sstream>
using std::cerr;
using std::cout;
using std::endl;
using std::ifstream;
using std::map;
using std::ofstream;
using std::string;
using std::stringstream;
class mapText
{
public:
    // 读文件,传入文件名,传出void
    void read(const string &filename);
    // 处理单词,传入单词字符串,传出字符串
    string dealword(string &word);
    // 保存处理好的字典文件,传入文件名,传出无参
    void store(const string &filename);

private:
    map<string, int> _map;
};
void mapText::read(const string &filename)
{
    // 绑定文件名与流
    // fstream ifs("china_daily.txt");
    ifstream ifs(filename);
    // 验证文件是否打开
    if (!ifs)
    {
        cerr << "open error!" << endl;
        return;
    }
    // 文本文件拆成一行一行的
    string line;
      string word;

    while (getline(ifs, line))
    { // 一行一行的处理为单词,每个单词存入word,处理单词合法性
        stringstream iss(line);
      
        while (iss >> word)
        {
            string newword = dealword(word);
            if (newword != string()) // 如果 newword 变量存储的值不是空字符串,则条件为真
            {
                // 将单词信息插入到map
                ++_map[newword]; // 多一个唯一的key:newword,value:int会++1
            }
        }
    }
    // 关闭文件流
    ifs.close();
}
string mapText::dealword(string &word)
{
    // 遍历word单词集合中的每一个单词
    // 如果不是单词,就用空串代替
    // 如果是大写就转为小写
    // 返回正确的单词
    for (int idx = 0; idx != word.size(); ++idx)
    {
        if (!isalpha(word[idx]))
        {
            return string();
        }
        else if (isupper(word[idx]))
        {
            word[idx] = tolower(word[idx]);
        }
    }
    return word;
}
void mapText::store(const string &filename)
{
    // 文件输出流和新文件名绑定
    // 检查文件打开是否正确
    // map类型迭代器初始化为begin
    // 遍历map,把map里面单词输入到ofs
    // 关闭ofs
    ofstream ofs(filename);
    if (!ofs)
    {
        cout << "open error!" << endl;
        return;
    }
    map<string, int>::iterator it = _map.begin();
    for (; it != _map.end(); ++it)
    {
        ofs << it->first << " " << it->second << endl;
    }
    ofs.close();
}
void test0()
{
    // 初始化对象
    mapText map1;
    // 时间戳
    time_t begin = time(NULL);
    // 对象调用read 把一个一个单词存入map 并统计词频
    map1.read("china_daily.txt");
    time_t end = time(NULL);
    // 处理好的单词放入新词典文件
    cout << "time: " << (end - begin) << "s" << endl;
    cout<<"11111111111111111"<<endl;
    map1.store("1.dat");
}

int main(void)
{
    test0();
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wuatt08

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值