词频统计改进版1

需求分析:从控制台读取文件并对文件中的词频进行统计,文件可以是自己输入也可以是指定目录自动读入。

功能一:从命令行读入文章:

功能二:手动输入单词并统计词频:

代码实现:

case 1:
        {
            fp=fopen("d:\\2.txt","w");
            ch=getchar();
            while(ch!='\n')
            {
                fputc(ch,fp);
                ch=getchar();
            }
            fclose(fp);
            fp=fopen("d:\\2.txt","r");
        }
        break;
    sum=0;
    map<string,int>list;
    while(fgets(text,1000,fp)!=NULL)
    {    
         i=0;
        while(text[i]!='\0')
        {
            char s[40];
            int k=0;
            while((text[i]>='A'&&text[i]<='Z')||(text[i]>='a'&&text[i]<='z'))
            {
                if(text[i]>='A'&&text[i]<='Z')
                text[i]+='a'-'A';
                s[k++]=text[i++];
            }
            s[k]='\0';//一个单词结束
            list[s]++;
            if(text[i]=='\0')break;//一行单词结束
            else i++;
            sum++;
        }
        
    }
    fclose(fp);
    map<string,int>::iterator m;
    cout<<"总共出现的单词数:"<<endl;
    cout<<sum<<endl;
    cout<<"每个词出现的频数如下:"<<endl;
    for(m=list.begin(),i=1;m!=list.end();i++,m++)
    {
        if(m->first=="")
        continue;

        cout<<left;
        cout<<setw(15)<<m->first<<setw(10)<<m->second;
        if(i%5==0)
        cout<<endl;
    }
    cout<<endl;

功能三:通过指定路径进行文件中单词词频统计

代码实现:

case 2:
        {
            cout<<"请输入所要统计词频的文章路径及文件名:"<<endl;
            cin>>str;
            fp=fopen(str,"r");
        }    
    sum=0;
    map<string,int>list;
    while(fgets(text,1000,fp)!=NULL)
    {    
         i=0;
        while(text[i]!='\0')
        {
            char s[40];
            int k=0;
            while((text[i]>='A'&&text[i]<='Z')||(text[i]>='a'&&text[i]<='z'))
            {
                if(text[i]>='A'&&text[i]<='Z')
                text[i]+='a'-'A';
                s[k++]=text[i++];
            }
            s[k]='\0';//一个单词结束
            list[s]++;
            if(text[i]=='\0')break;//一行单词结束
            else i++;
            sum++;
        }
        
    }
    fclose(fp);
    map<string,int>::iterator m;
    cout<<"总共出现的单词数:"<<endl;
    cout<<sum<<endl;
    cout<<"每个词出现的频数如下:"<<endl;
    for(m=list.begin(),i=1;m!=list.end();i++,m++)
    {
        if(m->first=="")
        continue;

        cout<<left;
        cout<<setw(15)<<m->first<<setw(10)<<m->second;
        if(i%5==0)
        cout<<endl;
    }
    cout<<endl;

ssh:git@git.coding.net:ziyoujay/cipintongji1.git

 

posted on 2016-09-13 16:26  自由jay  阅读(164)  评论(2编辑  收藏  举报