-
Notifications
You must be signed in to change notification settings - Fork 0
/
word_freq_cnt.cc
49 lines (44 loc) · 1.54 KB
/
word_freq_cnt.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream> /* std::cout */
#include <fstream> /* std::ifstream */
#include <sstream> /* std::istringstream */
#include <cstring> /* strtok */
#include <iomanip> /* std::setw */
#include <cmath> /* pow */
#include <cassert> /* assert */
#include <algorithm> /* std::max */
#include <string> /* std::string */
#include <map> /* std::map container */
using namespace std;
//https://github.com/thanthese/count-word-frequencies/blob/master/wordsInAFile.py
bool second_comp(const pair<string, int> &a, const pair<string, int> &b)
{
return a.second < b.second;
}
void word_counter(const char *filename, int max_cnt)
{
ifstream instream;
string line;
std::string word;
std::map<std::string, int> word_map;
/* Input stream should have only letters */
instream.imbue(std::locale());
instream.open(filename);
while(instream >> word)
++word_map[word];
/* Iterate over the map DS and print the top words */
for(auto it = word_map.cbegin(); it != word_map.cend() && max_cnt--; ++it)
{
cout << it->first << " : " << it->second << endl;
}
instream.close();
}
int main(int argc, char *argv[])
{
if(argc != 3) {
cerr << "Usage: " << argv[0] << " <file_name> <max_words>"
<< endl;
return -1;
}
word_counter(argv[1], atoi(argv[2]));
return 0;
}