python哈姆雷特词频统计

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

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)
for i in range(10):
     word,count = items[i]
     print("{0:<10}{1:>5}".format(word,count))

python哈姆雷特词频统计_第1张图片

转载于:https://my.oschina.net/zhangshsURL/blog/3009114

你可能感兴趣的:(python哈姆雷特词频统计)