天天看點

對哈姆雷特進行詞頻統計

def getText():

    txt = open("C:/Users/Administrator/Desktop/python-lianxi/hamlet.txt", "r").read()

    txt = txt.lower()   #首先把所有字母都轉換成小寫字母

    for ch in  '!"#$%()*+,-./:;<=>?@[\\]^_{|}·~‘’':   #排除掉英文字元,用空格替換

        txt = txt.replace(ch, " ")

    return txt

hamletTxt = getText()

words = hamletTxt.split()   #通過split函數用空格進行拆分

counts = {}

for word in words:

    counts[word] = counts.get(word,0) + 1   #字典的get方法,查找是否有鍵word,有則傳回其對應鍵值,沒有則傳回後面的值0

items = list(counts.items())

items.sort(key=lambda x:x[1], reverse=True)  #清單的排序常用搭配,将元素的下标為第一個的元素作為關鍵字按照從大到小排序

for i in range(10):

    word,count = items[i]

    print("{0:<10}{1:>5}".format(word, count))

Py