文本詞頻統計 -- Hamlet
Hamlet下載
鏈接:https://pan.baidu.com/s/1Is2mBAED57i6nI38lcnXAA
提取碼:zqw1
def getText():
txt = open("hamlet.txt","r").read() #打開文件 r 讀權限
txt = txt.lower() #把英文字母全部變成小寫
for ch in '!"$%&()*+,-./:;<=>?@[\\]^_{}|·`''':
txt = txt.replace(ch," ") #特殊符號替換為空格
return txt
hamletTxt = getText()
words = hamletTxt.split() #split默認以空格為分隔符,返回列表
counts = {} #定義一個空字典類型,因為一個單詞和對應的出現次數
for word in words: #循環取出單詞放到空字典當作key
counts[word] = counts.get(word,0) +1 #用key查詢出現次數,每出現一次+1(如果不存在返回0)
items = list(counts.items()) #取出字典的鍵和值 並返回列表類型
print(items) #[('the', 1138), ('tragedy', 3)]
items.sort(key=lambda x:x[1],reverse=True) #排序字典中的value,出現次數
for i in range(10):
word,count = items[i]
print("{0:<6}{1:>9}".format(word,count))