coding-文本的词频统计

题目

给定一英文文本文件data.dat,编写C++程序,读取文件中的内容,统计文件中出现次数最多的三个单词,并给出这三个单词的出现次数,同时输出程序运行的时间。(注: 这里不区分单词大小写,如, he 与 He 当做是同一个单词计数)

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
//#include <algorithm>
#include <conio.h>
#include <Windows.h>

using namespace std;

struct count
{
    string word;
    int num;
};

int main()
{
    long t1 = GetTickCount();

    vector<count> v;
    count tempstr;
    ifstream in("data.dat");
    string temp; //缓冲区
    string str;
    int count=0;
    int j=0;

    while(getline(in,temp)) //文件读取结束时退出循环
    {
        //transform(temp.begin(), temp.end(), temp.begin(), tolower); // 转换为小写,头文件冲突?
        for(int i=0; i<temp.length(); i++)
        {
            for(; i<temp.length(); i++)
            {
                if( (temp[i]>='a'&&temp[i]<='z') || (temp[i]>='A'&&temp[i]<='Z') )
                {
                    temp[i]=tolower(temp[i]); //转换成小写
                    count++;
                }else
                    break;
            }
            if(count)
            {
                str=temp.substr(i-count,count);
                if(v.size())
                {
                    for(j=0; j<v.size(); j++)
                    {
                        if(str.compare(v[j].word)==0)
                        {
                            v[j].num++;
                            count=0;
                            break;
                        }
                    }
                }
                if(j>=v.size())
                {
                    tempstr.word = str;
                    tempstr.num = 1;
                    v.push_back(tempstr);
                    count=0;
                }
            }

        }
    }

    int glass=0,n=v.size();
    string glastr;
    for(int i=0; i<3; i++)
    {
        for(int k=0; k<=n-2-i; k++)
        {
            if(v[k].num>v[k+1].num)
            {
                glass=v[k].num;
                v[k].num=v[k+1].num;
                v[k+1].num=glass;

                glastr=v[k].word;
                v[k].word=v[k+1].word;
                v[k+1].word=glastr;
            }
        }
    }

    cout<<"出现次数前三:"<<endl;
    for(int i=1; i<=3; i++)
    {
        cout<<v[n-i].word<<"   出现"<<v[n-i].num<<"次"<<endl;
    }


    long t2 = GetTickCount();
    cout<<"totle time:"<<t2-t1<<"s"<<endl;

    getch();
    return 0;
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值