词频统计Python 学生29思政课23
输入格式:
输入给出一段非空文本,最后以符号#结尾。输入保证存在至少10个不同的单词。
输出格式:
在第一行中输出文本中所有不同单词的个数。注意“单词”不区分英文大小写,例如“PAT”和“pat”被认为是同一个单词。
随后按照词频递减的顺序,按照词频:单词的格式输出词频最大的前10%的单词。若有并列,则按递增字典序输出。
输入样例:
This is a test.
The word "this" is the word with the highest frequency.
python 正则表达式 空格
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.
# 导入库
import re
import collections
import sys
words = "".join([line for line in sys.stdin]) # 标准输入sys.stdin读入文本
words = repile(r"\w+", re.I).findall(words.lower().split('#')[0]) # 正则表达式将文本处理成全小写并读到符号#
words = [each.strip() for each in words] # 去除空格
words = list(map(lambda each: each[0:15] if len(each) > 15 else each, words)) # 长度超过15的单词将只截取保留前15个单词字符
counter = collections.Counter(words) # 使用Counter统计词频
rank = sorted(counter.items(), key=lambda each: (-each[1], each[0]), reverse=False) # 按照词频递减排序
print(len(rank)) # 输出不同单词的个数
for each in rank[0:int(0.1*len(rank))]: # 输出词频最大的前10%的单词
print("{}:{}".format(each[1], each[0]))