首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算重复单词出现次数的程序

计算重复单词出现次数的程序
EN

Stack Overflow用户
提问于 2012-12-16 23:10:07
回答 1查看 741关注 0票数 0
代码语言:javascript
复制
#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,则该单词作为重复单词传递。但是当我运行它时,它没有显示任何重复的单词,尽管我甚至手动计算并知道文档中有重复的单词。我找不出问题所在。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-17 00:04:14

首先,当您无法打开输入文件时,应该将main的其余部分exit或包装到else中

代码语言:javascript
复制
if (fin.fail())
{
    cout<<"Error opening file!"<<endl;
}

否则,您将继续尝试从无效的流中读取。

你用std::getline和一个空白的' '作为分隔符来读你的单词。这意味着,在您的文字中包含换行符'\n'、制表符'\t'等,这可能不是您想要的。一种更好、更安全的阅读文字的方法是

代码语言:javascript
复制
std::string word;
while (fin >> word) {
    // process word
}

这将跳过所有空格,并正确检测EOF,这是一个额外的好处。

可能还会有更多的问题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13902585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档