# 代码中的‘标题.txt’是自己的文本数据
import jieba
counts = {} # 通过键值对的形式存储词语及其出现的次数
with open('./标题.txt','r',encoding='gbk') as f:
con = f.readlines()
for i in con:
words = jieba.lcut(i)
for word in words:
if len(word) == 1: # 单个词语不计算在内
continue
else:
counts[word] = counts.get(word, 0) + 1 # 遍历所有词语,每出现一次其对应的值加 1
items = list(counts.items())#将键值对转换成列表
items.sort(key=lambda x: x[1], reverse=True) # 根据词语出现的次数进行从大到小排序
#range中的30指的是输出词频前30的词
for i in range(30): #
word, count = items[i]
print("{0:<5}{1:>5}".format(word, count))
基于python的词频统计
最新推荐文章于 2022-06-21 13:05:17 发布