题目描述
请编写程序,对一段英文文本,统计其中所有不同单词的个数,以及词频最大的前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个单词中的前两个),而按照字典序,the排第三位,所以不输出)
23
5:this
4:is
代码:
#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
map<string,int> m;
vector<pair<string,int> > v;
bool Cmp(pair<string,int> a,pair<string,int> b){
if(a.second!=b.second){
return a.second>b.second;
}
else{//出现次数相同
return a.first<b.first;
}
}
int main(){
string word;
char str[100];
char ch;
int index=0;//记录每个单词的下标
map<string,int>::iterator it;
while(ch=getchar()){
if(ch=='#')break;
if(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z'||ch>='0'&&ch<='9'||ch=='_'){//可构成单词
if(ch>='A'&&ch<='Z'){//题目要求不区分大小写字母
ch=ch-'A'+'a';
}
str[index++]=ch;
}
else{//读入分隔符
if(index>0){//有单词读入
if(index>15){//截取
index=15;
}
str[index]='\0';//设置字符串结束符
word=str;
index=0;//准备读取下一个单词
it=m.find(word);
if(it!=m.end()){//找到
(it->second)++;
}
else{
m[word]=1;
}
}
}
}
//所有单词及其出现情况均保存在m中
for(it=m.begin();it!=m.end();it++){
v.push_back(make_pair(it->first,it->second));
}
sort(v.begin(),v.end(),Cmp);
int size=v.size()/10;
cout<<v.size()<<endl;
vector<pair<string,int> >::iterator iv;
for(iv=v.begin();iv!=v.begin()+size;iv++){
cout<<iv->second<<":"<<iv->first<<endl;
}
return 0;
}