在.txt文件上计算重复单词的C 程序
C++ program that counts repeated words on a .txt file
我正在尝试构建一个程序,该程序在.txt文件上计算重复单词,并输出重复的单词以及重复多少次。我有一种方法可以计算有多少个单词,但不是重复的单词。这是代码:
#include <iostream>
#include <string>
#include <math.h>
#include <iomanip>
#include <fstream>
#include <vector>
#include "ProcessStatistics.h"
using namespace std;
ProcessStatistics::ProcessStatistics()
{
//constructor
}
//Finds out how many words are composed by an specific number of characters.
void ProcessStatistics::Length(std::vector<std::string> ArrayOfWords, int numberOfWords)
{
cout << "=== COMPUTING WORD S LENGTH ==== " << endl;
int vectorLength[30] = {0};
for(int i = 0; i < numberOfWords; i++)
{
for(int j = 0; j<20; j++)
{
if (ArrayOfWords [i].length()-1 == j)
vectorLength[j] = vectorLength[j]+1;
}
}
ofstream varlocal;
remove("WORDS_LENGTH.txt");
varlocal.open("WORDS_LENGTH.txt");
if(varlocal.is_open())
{
varlocal << "Total: " << numberOfWords << endl;
for(int i=0; i < 30; i++)
{
if(vectorLength[i] != 0)
{
varlocal << vectorLength[i] << " W " << i+1 << " CHAR " << " % " << setprecision(3) << vectorLength[i]*100/numberOfWords << endl;
}
}
}
varlocal.close();
这是一些示例代码,可以使用 std::map
在文本文件上演示单词统计信息。
#include <algorithm>
#include <string>
#include <fstream>
#include <iostream>
using std::ifstream;
using std::cout;
using std::string;
using std::cin;
using std::map;
int main()
{
static const char filename[] = "my_data.txt";
ifstream input(filename);
if (!input)
{
cout << "Error opening data file " << filename << "n";
return 1;
}
map<string, unsigned int> word_data;
string word;
while (input >> word)
{
if (word_data.find(word) != word_data.end())
{
word_data[word]++;
}
else
{
word_data[word] = 1;
}
}
map<string, unsigned int>::iterator iter;
for (iter = word_data.begin(); iter != word_data.end(); ++iter)
{
cout << iter->second << "t" << iter->first << "n";
}
return 0;
}
在上述代码中,word
是map
中的密钥。单词出现,计数或频率是map
中的 value 。
如果单词存在于map
中,则计数会增加。如果单词不存在,则将其添加到map
中,计数为1。
读取文件后,打印了统计信息,计数后面是单词。
相关文章:
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- 该程序将.csv文件中的一系列单词放入数组中,然后随机生成句子.但它不起作用
- C ++程序在字符数组中插入单词
- 如何制作一个程序,它使用特定单词加密和解密消息?
- 我们如何重新制作程序以打开xml文件并在价格单词之后读取百分比值并更改此值
- 如何在程序中实现单词跳过解决方案
- C++入门第5版:单词转换程序
- 创建程序以从给定的.txt文件中查找文本,替换并计算单词
- C++:如果用户输入数字将其转换为单词,并且如果按回车键程序应退出,则使用开关大小写
- 为什么我的程序跳过重复单词的索引
- 尝试创建一个读取.txt文件,显示它,计数唯一单词的程序,并在使用了多少次的情况下显示独特的单词.C
- 用于获取以元音和辅音开头的单词数量的程序返回错误的答案
- 在.txt文件上计算重复单词的C 程序
- 尝试在C 中编写Pig Latin程序,我无法将字符串的单个单词纳入CSTRING中,无法编辑
- C++程序需要行单词和字符计数
- 使用 getline() 无限运行的匹配单词 c++ 程序
- C++ 具有两个类的拼写检查程序;字典和单词
- 内联程序集 - 检查单词是否为回文
- 我如何修改我的C 程序以显示用户输入的单词,并使用堆栈向后