计算单词出现次数
Count word occurances
在我的程序中,我读取文本文件,然后小写所有,并将它们分开,并附加到字符串。
using namespace std;
int main() {
int lines=0,i=0,k=0;
FILE *pfile=fopen("myfile.txt", "r");
char line2[500];
char * tok;
string alltext[999];
string words[999];
if(!pfile){printf("Errorn");return 1;}
std::string line;
std::ifstream myfile("eriala.txt");
while (std::getline(myfile, line))
++lines;
for(i=0;i<lines;i++){
fgets(line2,sizeof(line2),pfile);
char * str = line2;
for (int i =0;i<strlen(line2); ++i){
line2[i]=tolower(line2[i]);}
tok = strtok(str," ,.!nt():;-");
while(tok !=NULL){
alltext[k].append(tok);
alltext[k].append("n");
tok=strtok(NULL," ,.!nt():;-");
k++;}}
for(int i=0;i<k;i++){
int amount=0;
for(int j=0;j<k;j++){
if(strcmp(alltext[i].c_str(),alltext[j].c_str())==0)
amount++;}
}
}
我需要做的是计算一个单词在文本文件中出现的次数。它就是这么做的。但是我需要按降序显示
下面是一个完整的c++ 11版本,它对单词进行计数并按降序打印:
#include <algorithm>
#include <cctype>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
int main ()
{
std::ifstream file ("myfile.txt"); // Try to open the file
if (!file)
{
std::cerr << "Error: Cannot open file myfile.txt" << std::endl;
return 1;
}
std::map<std::string, std::size_t> word_counter;
std::string word;
while (file >> word) // While a word can be read
{
// Remove every character that is not an alphanumeric one
word.erase(std::remove_if(std::begin(word), std::end(word), [](char c) { return !::isalnum(c); }), std::end(word));
if (!word.empty())
{
// Lower case the word
std::transform(std::begin(word), std::end(word), std::begin(word), ::tolower);
// Increment the counter for this word
word_counter[word]++;
}
}
// Print the counted words in descending order
for (auto it = word_counter.crbegin() ; it != word_counter.crend() ; ++it)
std::cout << it->first << " => " << it->second << std::endl;
}
相关文章:
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- 当字符串是某个单词时给出输出?
- 计算出有多少客户端可以连接到我正在使用的一些tcp服务器代码
- 计算单词中的音节数,但考虑到单词中彼此相邻的任何元音都算作一个音节
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- C++ 计算数组中的单词
- 计算一个单词在映射中出现的次数 - 使用 transform() - 调用不匹配
- 我的C++级数计算程序出了什么问题?被困了好几个星期
- C++编译器能在编译时计算出文字的除法结果吗
- 从文件中找出字符'a',然后计算字符出现的行数
- 使用结构数组计算文本文件中单词的出现次数C++
- 复合赋值的左侧表达式是未初始化的值.计算出的值也将是垃圾
- 创建程序以从给定的.txt文件中查找文本,替换并计算单词
- 计算单词中的字母
- 我想知道我将如何实现 + 运算符重载.我已经从我上一个问题中计算出 += 运算符重载
- 计算段落中出现次数最多的单词
- log2 计算在 CPP 中给出了错误的结果
- 我如何计算一个单词在数组中重复的次数
- 如何计算出现在字符串和输出行中的唯一单词?C
- 额外的单词出现在visualc++输出窗口