写一个程序分析文本文档(英文文章)中各个词出现的频率并把频率最高的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);
}

posted @ 2014-03-02 20:26  何晓楠  阅读(412)  评论(1编辑  收藏  举报