字典查找

读取Txt,统计某个关键字出现的次数,并将其所在的行打印出来


///
 /// @file    TextQuery.cc
 /// @author  miaobeihai(452686191@gmail.com)
 /// @date    2017-05-01 10:55:06
 ///

#include <assert.h>
#include <ctype.h>

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>  //string-->  vector<char>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <functional>


using std::cout;
using std::endl;
using std::string;
using std::set;
using std::map;
using std::vector;
using std::ifstream;
using std::istringstream;
using std::replace_if;

static_assert(sizeof(void*) == 8, "not supported");

class TextQuery
{
public:
	TextQuery();
	void readFile(const string & filename);
	void query(const string & word);
private:
	static const int kInit = 100;
	vector<string> _lines;
	map<string, int> _dict;
	map<string, set<int> > _word2Line;
};

TextQuery::TextQuery()
{
	_lines.reserve(kInit);
}


struct NotAlpha //: public std::unary_function<char, bool>
{
	bool operator()(char ch) const
	{
		return (!isalpha(ch));
	}
};

struct IsAlpha : public std::unary_function<char, bool>
{
	bool operator()(char ch) const
	{
		return (isalpha(ch));
	}
};


void test()
{
	//char * p = NULL;
	//assert(p != NULL);//使用assert断言,运行时断言
	//(void)p;
	//static_assert((p != 0), "nullptr exception");// 编译时断言, 必须要求是一个常量表达式
	//static_assert(sizeof(p) == 8, "不支持32位系统");//只在编译时起作用,代码不会进入到源码
}


void TextQuery::readFile(const string & filename)
{ 
	ifstream ifs(filename);
	assert(ifs);//assert方法可以多使用,用来判断指针或者对象初始化是否异常

	string line;
	int cnt = 0;
	while(getline(ifs, line))
	{ 
		_lines.push_back(line);
		
		//replace_if(line.begin(), line.end(), std::not1(isalpha), ' ');//Error
		replace_if(line.begin(), line.end(), NotAlpha(), ' ');
		//replace_if(line.begin(), line.end(), std::not1(IsAlpha()), ' ');

		cout <<  cnt << ":" << line << endl;

		istringstream iss(line);
		
		string word;

		while(iss >> word)
		{
			++_dict[word];
			
			_word2Line[word].insert(cnt);
		}
		++cnt;
	}
	ifs.close();
}

void TextQuery::query(const string & word)
{
	int freq = _dict[word];
	cout << word << " occurs " << freq << (freq > 0 ? " times.":" time.") << endl;
	set<int> & lines = _word2Line[word];
	for(auto & elem : lines)
	{
		cout << "    (line " << elem + 1 << ")" << _lines[elem] << endl;
	}
}

int main(void)
{
	TextQuery tq;
	tq.readFile("china_daily.txt");
	tq.query("still");

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值