def getText():
txt = open("hamlet.txt","r").read()#打开文本
txt = txt.lower()
for ch in """~`!@#$%^&*()_+=-[]{}\|:;"/?.>,<\'""":
txt = txt.replace(ch," ")
#归一 去噪
return txt
hamletTxt = getText()
counts = {}
words= hamletTxt.split()
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):
word,count = items[i]
print("{:<10}{:>5}".format(word,count))
key=lambda 元素: 元素[字段索引]
x:x[]字母可以随意修改(但要一致 如:y:y)
排序方式按照中括号[]里面的维度进行排序,[0]按照第一维排序,[1]按照第二维排序