#include <iostream>
#include <vector>
#include <cstring>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
vector<string> Letter;
float frequency1(string word)
{
float count=0.0;
for (int i=0;i<Letter.size();++i)
{
transform(word.begin(),word.end(),word.begin(),::tolower);
transform(Letter[i].begin(),Letter[i].end(),Letter[i].begin(),::tolower);
if (strcmp(word.c_str(),Letter[i].c_str())==0)
{
count+=1;
}
}
count=(count/Letter.size())*100;
if (count>=0.5)
{
return count;
}
else
{
return 0.0;
}
}
int main()
{
ifstream fin;
fin.open("frequent.txt");
if (fin.fail())
{
cout<<"Error opening file!"<<endl;
}
while(!fin.eof())
{
string buffer;
getline(fin,buffer,' ');
cout<<buffer<<endl;
Letter.push_back(buffer);
}
cout<<endl;
vector<string> frequent;
vector<float> frequency;
for (int i=0;i<Letter.size();++i)
{
string a=Letter[i];
int k=0;
for (int j=0;j<i;++j)
{
transform(a.begin(),a.end(),a.begin(),::tolower);
transform(Letter[j].begin(),Letter[j].end(),Letter[j].begin(),::tolower);
if (a==Letter[j])
{
break;
}
k++;
}
int size=Letter.size();
if (k!=size-1)
{
continue;
}
float counter=frequency1(a);
if(counter>0.0)
{
frequent.push_back(Letter[i]);
frequency.push_back(counter);
}
}
cout<<"Here are the repeated words"<<endl;
for (int i=0;i<frequency.size();++i)
{
cout<<" "<<frequent[i]<<", frequency: "<<frequency[i]<<endl;
}
system("PAUSE");
return 0;
} 我正在写一个程序,它可以确定文档(文本)中重复单词的频率。如果频率大于或等于0.5,则该单词作为重复单词传递。但是当我运行它时,它没有显示任何重复的单词,尽管我甚至手动计算并知道文档中有重复的单词。我找不出问题所在。
发布于 2012-12-17 00:04:14
首先,当您无法打开输入文件时,应该将main的其余部分exit或包装到else中
if (fin.fail())
{
cout<<"Error opening file!"<<endl;
}否则,您将继续尝试从无效的流中读取。
你用std::getline和一个空白的' '作为分隔符来读你的单词。这意味着,在您的文字中包含换行符'\n'、制表符'\t'等,这可能不是您想要的。一种更好、更安全的阅读文字的方法是
std::string word;
while (fin >> word) {
// process word
}这将跳过所有空格,并正确检测EOF,这是一个额外的好处。
可能还会有更多的问题。
https://stackoverflow.com/questions/13902585
复制相似问题