PTA 词频统计

404 阅读2分钟

请编写程序,对一段英文文本,统计其中所有不同单词的个数,以及词频最大的前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<string>

using namespace std;

map<string, int> mp;
int num = 0;

void pushMap(string& s, int& n)
{
	if (mp[s] == 0)
	{
		num++;
		mp[s] = 1;
	}
	else
		mp[s]++;
	s = "";
	n = 0;
}

int main()
{
	string s, word;
	int n = 0, m = 0;
	while (cin >> s)
	{
		for (int i = 0; i < s.length(); i++)
		{
			if (s[i] == '#')
			{
				if (i == s.length() - 1 && n > 0)
					pushMap(word, n);
				cout << num << endl;
				int sum = num / 10;
				for (int j = 0; j < sum; j++)
				{
					int MAX_num = 0;
					string MAX_s;
					for (map<string, int>::iterator k = mp.begin(); k != mp.end(); k++)
					{
						if (k->second > MAX_num)
						{
							MAX_num = k->second;
							MAX_s = k->first;
						}
					}
					cout << MAX_num << ':' << MAX_s << endl;
					mp.erase(MAX_s);
				}

				return 0;
			}
			if (n == 15)
			{
				pushMap(word, n);
				break;
			}
			if (s[i] >= 'A' && s[i] <= 'Z')
			{
				word += s[i] + 32;
				n++;
			}
			else if (s[i] >= 'a' && s[i] <= 'z' || s[i] >= '0' && s[i] <= '9' || s[i] == '_')
			{
				word += s[i];
				n++;
			}
			else
			{
				if (n > 0)
				{
					pushMap(word, n);
					continue;
				}
			}
			if (i == s.length() - 1 && n > 0)
			{
				pushMap(word, n);
			}
		}
	}
	return 0;
}

提交结果:

7.png