当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 【PTA-天梯赛选拔】词频统计

【PTA-天梯赛选拔】词频统计

2018年03月18日  | 移动技术网IT编程  | 我要评论

中国银行金价,快递单号88dan,在妓院里出生的男人

请编写程序,对一段英文文本,统计其中所有不同单词的个数,以及词频最大的前10%的单词。

所谓“单词”,是指由不超过80个单词字符组成的连续字符串,但长度超过15的单词将只截取保留前15个单词字符。而合法的“单词字符”为大小写字母、数字和下划线,其它字符均认为是单词分隔符。

输入格式:

输入给出一段非空文本,最后以符号#结尾。输入保证存在至少10个不同的单词。

输出格式:

在第一行中输出文本中所有不同单词的个数。注意“单词”不区分英文大小写,例如“PAT”和“pat”被认为是同一个单词。

随后按照词频递减的顺序,按照词频:单词的格式输出词频最大的前10%的单词。若有并列,则按递增字典序输出。

输入样例:

This is a test.

The word "this" is the word with the highest frequency.

Longlonglonglongword should be cut off, so is considered as the same as longlonglonglonee.  But this_8 is different than this, and this, and this...#
this line should be ignored.

输出样例:(注意:虽然单词the也出现了4次,但因为我们只要输出前10%(即23个单词中的前2个)单词,而按照字母序,the排第3位,所以不输出)

23
5:this
4:is

题解:

一道map计数题,其中用到了pair。

将map里的元素逐一转至pair,再将pair元素转至vector,最后用vector进行排序!!

【关于Pair与map】

① map是pair的集合,也就是说map的元素是pair。

② map会自动根据value的值以升序排序(从小到大排序)

③ pair的first成员是map的key,second成员是map的value。

④ pair被定义为struct类型。

⑤ p.first      (p中的first的公有数据成员)

⑥ p.second(p中的second的公有数据成员)

#include<bits/stdc++.h>
#define p pair<string,int>  //定义了一个pair p 
using namespace std;
bool cmp(p a,p b)
{
    if(a.second>b.second)   //先以单词数量从大到小排序 
        return true;
        
    if(a.second==b.second)  //如果数量相等 
        if(a.first<b.first) //再以字典序升序排序 
            return true;
            
    return false;
}
int main()
{
    map<string,int> ma;
    map<string,int>::iterator it; 
    vector<p> v;            //vector为pair类型
    string s;
    char ch;
    while(1) 
    {
        ch=getchar();       //用getchar暂存字符 
        if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||(ch>='0'&&ch<='9')||(ch=='_'))
        {
            if(s.size()<=14)  
            {
                if(ch>='A'&&ch<='Z')   //如果是大写字母,则变成小写 
                    ch+=32;
                s+=ch;                 //将字符放入string s 
            }
        }
        else
        {
            if(s.size()>0) 
                ma[s]++;               //将字符串存到map中 
            s.clear();
        }
        if(ch=='#')break;
    }
    for(it=ma.begin();it!=ma.end();it++)
    {
        v.push_back(p(it->first,it->second));   //将map元素赋值到p,p作为中转器赋值到vector 
    }
    sort(v.begin(),v.end(),cmp);       //用vector排序!!!! 
    cout<<ma.size()<<endl;             //用map的size计算不同单词数量 
    int cnt=(int)(ma.size()*0.1);      //前10%的单词
     
    for(int i=0;i<cnt;i++)
        cout<<v[i].second<<':'<<v[i].first<<endl;
    return 0;
}

 

最后感谢一波 @大桃桃 提供的做法

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网