python _ 统计红楼梦人员姓名出现次数
使用到jieba库 --Python 第三方中文分词库
1 安装jieba库 ;
2 红楼梦 TXT 文档
import jieba
txt = open ("红楼梦.txt","r",encoding='utf-8').read()
wenben =jieba.lcut(txt) #使用精确模式对文本进行分词
counts ={} # 通过键值对的形式存储词语及其出现的次数
# 类似于 {'a': 1, 'b': 1, 'c': 1, 'd': 1}
for word in wenben:
if len(word) ==1: # 单个词语不计算在内
continue
else:
counts[word]=counts.get(word,0)+1 # 遍历所有词语,每出现一次其对应的值加 1
temp = list(counts.items()) # items() 函数以列表返回可遍历的(键, 值) 元组数组 #字典的键值对变成列表
temp.sort(key=lambda x:x[1] , reverse=True) # 根据词语出现的次数进行从大到小排序
for i in range(15):
word , count=temp[i]
print ("{0:<10}".format(word,count))
# 0表示word <10表示左对齐,并占10个位置
#format按{word count}输出