创建文本文件中出现的前10个单词的直方图
Create a histogram of the top 10 words that appear in a text file
我正在尝试创建一个文本中前十个单词出现频率的直方图(以百分比为单位)。它需要采用与此类似的格式:
用于:-------------------20(百分比和20个破折号)
是:---------------15
他:----------10
战争:-----5
有:-----5
英雄:-----5
有:----4
女孩:-----5
愤怒:----4
其他:-------------------------------32
我知道我需要一个10的for循环,在它里面还有一个带破折号的循环,去百分比
int main(){
string file_name;
cout << "Enter the file name, the odyssey or pride and prejudice, that you would like to analyze: ";
getline(cin,file_name);
vector<string> words; //loading words into vector called words
if(file_name == "test")
{
words = words_to_vector("test.txt"); //used a test files so it would take less time
}
else if(file_name == "pride and prejudice")
{
words = words_to_vector("pride-prejudice.txt");
}
else if (file_name == "the odyssey")
{
words = words_to_vector("the-odyssey.txt");
}
else
{
cout << "Sorry, the file name you entered is invalid.";
}
vector<word_stats> stats = get_word_stats(words); // calculating the number of words, and how many of those words are unique
cout << endl << endl << "Total words: " << words.size() << ", " << stats.size() << " unique" << endl;
sort(stats.begin(), stats.end(), compare_stats);
cout << "Most common word is '" << stats[0].word << "' occuring " << stats[0].count << " times." << endl;
int topMostCount = 10; //where I need help putting this into a histogram
//int totalWords = words.size();
int totalUniqueWords = stats.size();
//most common
for (int i=0; i<stats.size() && i<topMostCount; i++) {
cout << stats[i].word << ": " << stats[i].count << endl;
}
创建一个生成破折号并将其输出为const char*的方法怎么样?
for(int i = 0; i < stats.size() && i < topMostCount; i++){
int percent = (double)stats[i].count / words.size * 100.00;
const char * dashes = genDashes(percent);
cout << stats[i].word << ": " << dashes << percent << "%";
}
genDashes函数如下所示:
const char * genDashes(int n)
{
std::stringstream ss_dashes;
for(int i = 0; i < n; i++){
ss_dashes << "-";
}
std::string s_dashes = ss_dashes.str();
return s_dashes.c_str();
}
相关文章:
- 我们如何在文本文件中找到C++中的几个单词?
- 将 10 个线程与原子布尔值同步
- 如何阅读两个单词,然后阅读C++中的一行?
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 如何使用运算符>>在自定义字符串中输入多个单词?
- 在文本中查找半个单词"ABBA"的问题
- 将 2 个单词与字符串分隔开
- 在C++中使用哪个函数来输入多个单词,比如C中的fgets
- 如何让用户C++输入少于 10 个元素的数组
- 如何让变量随机输出四个单词之一
- 如何将行的第一个单词作为一个变量,将行的其余部分作为另一个变量进行归档/存储
- 当字符串中只有一个"GOOD"字符串可用时,从没有空格的字符串中提取第一个单词的最佳和有效方法?
- CPP - strlen 不会输出多个单词的整个长度 [仅限 C 字符串]
- QT 创建器只会将第一个单词从文本编辑转换为纯文本
- 二叉树插入功能不适用于 10 个条目
- 从文件的一行中查找数字的平均值,避免使用第一个单词
- 在文件中查找 10 个最长的单词
- 从文件 (C++) 输入两个单词字符串
- 视觉C++查找以 "ing" 结尾且少于或等于 10 个字符的单词
- 创建文本文件中出现的前10个单词的直方图