词频统计改进版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

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值