统计文章内各个单词出现的次数
2016-09-08 16:10
309 查看
算法的思路是:
从头到尾遍历文件,从文件中读取遍历到的每一个单词。
把遍历到的单词放到hash_map中,并统计这个单词出现的次数。
遍历hash_map,将遍历到的单词的出现次数放到优先级队列中。
当优先级队列的元素个数超过k个时就把元素级别最低的那个元素从队列中取出,这样始终保持队列的元素是k个。
遍历完hash_map,则队列中就剩下了出现次数最多的那k个元素。
具体实现和结果如下:
从头到尾遍历文件,从文件中读取遍历到的每一个单词。
把遍历到的单词放到hash_map中,并统计这个单词出现的次数。
遍历hash_map,将遍历到的单词的出现次数放到优先级队列中。
当优先级队列的元素个数超过k个时就把元素级别最低的那个元素从队列中取出,这样始终保持队列的元素是k个。
遍历完hash_map,则队列中就剩下了出现次数最多的那k个元素。
具体实现和结果如下:
算法的思路是: 从头到尾遍历文件,从文件中读取遍历到的每一个单词。 把遍历到的单词放到hash_map中,并统计这个单词出现的次数。 遍历hash_map,将遍历到的单词的出现次数放到优先级队列中。 当优先级队列的元素个数超过k个时就把元素级别最低的那个元素从队列中取出,这样始终保持队列的元素是k个。 遍历完hash_map,则队列中就剩下了出现次数最多的那k个元素。 具体实现和结果如下: [cpp] view plain copy print? // 出现次数最多的K个单词.cpp : Defines the entry point for the console application. #include "stdafx.h" #include <hash_map> #include <string> #include <fstream> #include <queue> #include <iostream> #include <algorithm> #include <boost/timer.hpp> using namespace std; using namespace boost; void top_k_words()//出现次数最多的是个单词 { timer t; ifstream fin; fin.open("modern c.txt"); if (!fin) { cout<<"can not open file"<<endl; } string s; hash_map<string,int> countwords; while (true) { fin>>s; countwords[s]++; if (fin.eof()) { break; } } cout<<"单词总数 (重复的不计数):"<<countwords.size()<<endl; priority_queue<pair<int,string>,vector<pair<int,string>>,greater<pair<int,string>>> countmax; for(hash_map<string,int>::const_iterator i=countwords.begin(); i!=countwords.end();i++) { countmax.push(make_pair(i->second,i->first)); if (countmax.size()>10) { countmax.pop(); } } while(!countmax.empty()) { cout<<countmax.top().second<<" "<<countmax.top().first<<endl; countmax.pop(); } cout<<"time elapsed "<<t.elapsed()<<endl; } int main(int argc, char* argv[]) { top_k_words(); system("pause"); return 0; }
相关文章推荐
- 统计文章内各个单词出现的次数
- 统计文章内各个单词出现的次数
- 统计文章内各个单词出现的次数 (STL)
- Python每日一练(1):计算文件夹内各个文章中出现次数最多的单词
- 统计一篇英文文章中出现次数最多的前五个单词
- java 统计10000篇文章中不同单词出现的次数并以次序排序
- 统计海量文章内容中出现次数前K大的单词并输出(完整实现)
- 统计文章中单词出现的次数
- java实现读取一篇英文文章,统计其中每个单词出现的次数并排序输出
- Linux作业(三)-shell统计某文章中出现频率最高的N个单词并排序输出出现次数
- Java统计一篇文章中出现次数最多的汉字或英文单词 又出现次数的统计
- python---在文本/文章中统计字符串中出现单词次数
- 统计文章中单词出现的次数(续)
- F# 统计一段英文文章中不同单词出现的次数
- 统计一篇文章中每个单词出现的次数
- java统计一篇文章中单词出现的次数
- Linux作业(三)-shell统计某文章中出现频率最高的N个单词并排序输出出现次数
- (转)F# 统计一段英文文章中不同单词出现的次数
- N个任务掌握java系列之统计一篇文章中单词出现的次数
- 输入文章,统计各个单词出现次数