代码
def getText():
txt=open("article.txt","r").read()
txt=txt.lower()
for ch in '~!@#$%^&*()_+"{}[]|?.<>?':
txt=txt.replace(ch,"")
return txt
hamletTxt=getText()
words=hamletTxt.split()
counts={}
for word in words:
counts[word]=counts.get(word,0)+1
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range (10): ###这里就让它输出10个看看得了
word,count=items[i]
print("{0:<10}{1:>5}".format(word,count))
此代码有效的前提是你创建了一个article.txt。在里面写上你要统计的单词。
(一定要将py和文章放在同一个地方)比如都放在桌面
运行效果如下