def getText():
txt = open("hamlet.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)
#這一步看不太懂
#lambda x:x[1] 我理解的是輸入一個序列x,輸出x的x[1]元素
#但為什么items.sort(key=lambda x:x[1], reverse=True)就是對序列進行排序了呢
#items.sort(key=lambda x:x[1])是什么意思呢?
for i in range(10):
word, count = items[i]
print ("{0:<10}{1:>5}".format(word, count))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/191147.html
上一篇:初學Python :為什么程式運行break到這就回傳while True進行又一次回圈了呢?
下一篇:【翻譯】一個威脅獵人的檢查清單
