#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;
}
使用map重写词频统计。(之前使用的vector,可以比较他们的速率)
最新推荐文章于 2024-07-15 13:32:43 发布