Jieba库:主要是将字符串分割成单词
import jieba
txt = open("threekingdoms.txt", "r", encoding="utf-8").read()
# jieba.lcut(str) 将str分成片,不重复
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) ==1:
continue
else:
# 如果word 不存在,则value默认为0
counts[word] = counts.get(word, 0)+1
# counts.items()是所有的键值对
items = list(counts.items())
items.sort(key=lambda x: x[1],reverse=True)
for i in range(15):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))