詞頻統計(30 分)
請編寫程序,對一段英文文本,統計其中所有不同單詞的個數,以及詞頻最大的前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
#include<stdio.h> #include<iostream> #include<string> #include<algorithm> #include<vector> using namespace std; struct node{ string s; int n; }; vector<node > q; bool cmp(node s1,node s2) { if(s1.n ==s2.n ) return s1.s <s2.s ; else return s1.n >s2.n; } //比較如果詞頻一樣,按字符從小到大排; int main() { char n; string s; while(scanf("%c",&n)) { if(n>='A'&&n<='Z'||n>='a'&&n<='z'||n>='0'&&n<='9'||n=='_') { if(n>='A'&&n<='Z') n=n+32; s+=n;//string可以直接相加 }//進行大小寫轉化,並累加字母為單詞; else if(n=='#'||s.size()>0) { string ss; if(s.size()>0) { int g=0; for(int i=0;i<15&&i<s.size();i++) { ss+=s[i]; } for(int i=0;i<q.size();i++) { if(q[i].s==ss) q[i].n++;//記錄單詞個數; g=1; } if(g==0) { node cc ; cc.n = 1; cc.s = ss; q.push_back(cc); }//如果是新單詞,新記錄; } s.clear(); //每次都空; if(n=='#') { break; } } } printf("%d\n",q.size());//單詞數 sort(q.begin(),q.end(),cmp);//進行排序 for(int i=0;i<q.size()/10;i++) printf("%d:",q[i].n),cout<<q[i].s,printf("\n"); }