如何统计出一篇文章出现的文字个数? (高级) (使用std::map)
1
/*
2
(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4
Filename : CountRepeaterByWordByMap.cpp
5
Compiler : Visual C++ 8.0
6
Description : Demo how to count repeated words by std::map
7
Release : 11/16/2006
8
*/
9
10
#include <iostream>
11
#include <fstream>
12
#include <cctype>
13
#include <string>
14
#include <map>
15
#include <algorithm>
16
17
void repeatedWords(std::string);
18
19
int main() {
20
std::string fileName("textfile.txt");
21
repeatedWords(fileName);
22
23
return 0;
24
}
25
26
void repeatedWords(std::string fileName) {
27
28
std::ifstream infile(fileName.c_str());
29
30
if (!infile) {
31
std::cout << "Read error!!" << std::endl;
32
33
return;
34
}
35
36
std::map<std::string, int> wordCount;
37
for(std::string word, newWord; infile >> word; ++wordCount[newWord], newWord="") {
38
for(std::string::iterator iter = word.begin(); iter != word.end(); ++iter) {
39
if (!ispunct(*iter)) {
40
newWord.push_back(tolower(*iter));
41
}
42
}
43
}
44
45
infile.close();
46
47
// cout the result
48
for(std::map<std::string, int>::iterator iter = wordCount.begin();
49
iter != wordCount.end(); ++iter) {
50
std::cout << "The Word '" << iter->first << "' Occurrence:" << iter->second << " times" << std::endl;
51
}
52
}
/* 2
(C) OOMusou 2006 http://oomusou.cnblogs.com3

4
Filename : CountRepeaterByWordByMap.cpp5
Compiler : Visual C++ 8.06
Description : Demo how to count repeated words by std::map7
Release : 11/16/20068
*/9

10
#include <iostream>11
#include <fstream>12
#include <cctype>13
#include <string>14
#include <map>15
#include <algorithm>16

17
void repeatedWords(std::string);18

19
int main() {20
std::string fileName("textfile.txt");21
repeatedWords(fileName);22

23
return 0;24
}25

26
void repeatedWords(std::string fileName) {27

28
std::ifstream infile(fileName.c_str());29

30
if (!infile) {31
std::cout << "Read error!!" << std::endl;32

33
return;34
}35

36
std::map<std::string, int> wordCount;37
for(std::string word, newWord; infile >> word; ++wordCount[newWord], newWord="") {38
for(std::string::iterator iter = word.begin(); iter != word.end(); ++iter) {39
if (!ispunct(*iter)) {40
newWord.push_back(tolower(*iter));41
}42
}43
}44

45
infile.close();46

47
// cout the result48
for(std::map<std::string, int>::iterator iter = wordCount.begin();49
iter != wordCount.end(); ++iter) {50
std::cout << "The Word '" << iter->first << "' Occurrence:" << iter->second << " times" << std::endl;51
}52
}


浙公网安备 33010602011771号