[Python] Hamlet word count

def getText(): #Give txt Hamlet novel-all English lowercase-all symbols to spaces-return txt 
txt = open('C:/Users/eternal/Desktop/hamlet.txt','r').read() # The path should be selected
txt = txt.lower()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
txt = txt.replace(ch," ")
return txt
hamletTxt = getText()
words = hamletTxt.split() #Return
counts with empty characters as a list = {}
for word in words:
counts[word] = counts.get(word ,0) + 1 #Create word as the subscript value 0+1 if the word is not obtained. If the get is reached, add 1 to the value of the word, and then update the dictionary
items = list(counts.items()) #Key of the dictionary The value pair becomes a list
items.sort(key=lambda x:x[1],reverse=True) #Order according to the number of occurrences, from large to small
print(items)
for i in range(10):
word,count = items[i]
print('{0:<10}{1:>5}'.format(word,count))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325252318&siteId=291194637