写一个程序分析文本文档(英文文章)中各个词出现的频率并把频率最高的10个词打印出来...

写一个程序分析文本文档(英文文章)中各个词出现的频率并把频率最高的10个词打印出

这个程序主要涉及识别、统计和排序,识别和统计采用结构体、结构体数组 ,排序时冒泡排序法。 由于单词存放用的数组所以会造成空间的浪费,存放单词个数,文章大时,空间可能不足,小时会浪费。冒泡排序法由于比较次数多,效率不会太高。

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct L{
    char a[30];
    int n;
};
int sum=0;
void read(struct L word[])
{
    ifstream in("text.txt");
    in>>noskipws;
    if(!in) {cout<<"cannot open!"<<endl;return;}
    char ch,temp[30];
    while(in)
    { 
        int i=0;
        in>>ch;
        temp[0]='\0';
        while((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||temp[0]=='\0')
        {
            if(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z')
            {
                temp[i]=ch;
                i++;
            }
            in>>ch;
            if(in.eof())break;
            
        }
        temp[i]='\0';
        for(i=0;i<sum;i++)
        {
            if(!_stricmp(temp,word[i].a)) 
            { word[i].n++;break;}
        }
        if(i==sum)
        {
                strcpy(word[sum].a,temp);
                word[sum].n=1;
                    sum++;


        }
    }
    in.close();
}
void sort(struct L word[])
{
    struct L temp;
    for(int i=0;i<sum-1;i++)
        for(int j=0;j<sum-1-i;j++)
            if(word[j].n<word[j+1].n)
            {
                strcpy(temp.a,word[j].a);
                temp.n=word[j].n;
                strcpy(word[j].a,word[j+1].a);
                word[j].n=word[j+1].n;
                strcpy(word[j+1].a,temp.a);
                word[j+1].n=temp.n;
            }
}
void out(struct L word[])
{
    if(sum>=10)
    for(int i=0;i<10;i++)
    {
        cout<<"单词"<<word[i].a<<"出现"<<word[i].n<<"次\n";
    }
}
int main()
{
    struct L word[10000];
    read(word);
    sort(word);
    out(word);
}

转载于:https://www.cnblogs.com/hexiaonan/p/hexiaonan.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值