统计出现频率最高的20个词,代码:
def getText():
txt = open('comment.text','r',encoding='utf-8').read()
txt = txt.lower()
for ch in '`~!@#$%^&*()_+-={}[];":,./<>?\|':
txt = txt.replace(ch," ")
return txt
commentText = getText()
words = commentText.split()
# print(words)
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)
print("出现频率最高的20个词:")
print("单词 出现次数")
for i in range(20):
word,count = items[i]
print("{0:<10}{1:>5}".format(word,count))
结果: