浙大版《Python程序设计》题目集(第七章)

第7章-1 词频统计

import math
strs = input()
while True:
    if strs[-1] != "#":
        strs = strs + "\n" + input()
    else:
        strs = strs[:-1]
        break
strs = strs.lower()
#print(strs)
for ch in '!"#$%&()*+,-.<=>?@[\\]^_`{|}~':
    strs = strs.replace(ch," ")
words = strs.split()
#print(words)
counts = {}
for word in words:
    if len(word) > 15:
        word = word[:15]
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key = lambda x:x[1],reverse = True)
print(len(items))
for i in range(math.floor(len(items) * 0.1)):
    word,count = items[i]
    print(count,word)
posted @ 2021-10-28 09:12  闲晚  阅读(144)  评论(0编辑  收藏  举报