项目场景:
Python练习题
解决方案:
提示:这里填写该问题的具体解决方案:
def gettest():
txt = open("hamlet.txt", 'r').read()
txt = txt.lower()
for ch in '!\"#$%&()*+,-./:;?@[\\]^_‘{|}~':
txt = txt.replace(ch, ' ')
return txt
hamelet = gettest()
words = hamelet.split()
count = {}
n = eval(input())
num = 0
for word in words:
count[word] = count.get(word, 0) + 1
items = list(count.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(10):
num += 1
word, count = items[i]
if num > n:
break
print("{0:5}".format(word, count))