習題5.13 詞頻統計 (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 <iostream>
#include <map>
#include <set>
#include <string>
using namespace std;

struct Node {
	string str;
	int count;
	bool operator<(const Node& s)const {
		return count == s.count ? str<s.str : count>s.count;
	}
};

int main() {
	set<Node>st;
	map<string, int>mp;
	string s;
	char c;
	while (scanf("%c", &c) && c != '#') {
		if (isalnum(c) || c == '_') {
			if (isalpha(c))
				c = tolower(c);
			s += c;
		}
		else if (s.size()) {
			if (s.size() > 15)
				s = s.substr(0, 15);
			mp[s]++;
			s.clear();
		}
	}
	for (auto& it : mp)
		st.insert({ it.first,it.second });
	int cnt = st.size();
	cout << cnt << endl;
	cnt /= 10;
	for (auto& it : st) {
		cout << it.count << ":" << it.str << endl;
		if (!--cnt)
			break;
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章