Created
April 14, 2015 01:33
-
-
Save Miliox/286731d08c4f63214145 to your computer and use it in GitHub Desktop.
Find Top N Words from a Text File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * topn_lite.cpp | |
| * Copyright (C) 2015 Emiliano Firmino <emiliano.firmino@gmail.com> | |
| * | |
| * Distributed under terms of the MIT license. | |
| */ | |
| #include <algorithm> | |
| #include <iostream> | |
| #include <fstream> | |
| #include <string> | |
| #include <unordered_map> | |
| #include <vector> | |
| int main(int argc, char ** argv) { | |
| std::fstream file; | |
| file.open(argv[1], std::fstream::in); | |
| std::unordered_map<std::string, unsigned int> dict; | |
| std::string word; | |
| while (file >> word) { | |
| std::transform(word.begin(), word.end(), word.begin(), ::tolower); | |
| auto value = dict.find(word); | |
| if (value == dict.end() ) | |
| dict.insert(std::make_pair(word, 1)); | |
| else | |
| dict[word] = value->second + 1; | |
| } | |
| std::vector<std::pair<std::string, unsigned int>> list(dict.begin(), dict.end()); | |
| std::sort(list.begin(), list.end(), | |
| [](const std::pair<std::string, unsigned int>& lhs, | |
| const std::pair<std::string, unsigned int>& rhs) { | |
| return lhs.second > rhs.second; | |
| }); | |
| for (const auto &w : list) { | |
| std::cout << w.first << " : " << w.second << "\n"; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment