红楼梦人物出场统计

小说下载地址:链接:https://pan.baidu.com/s/140JKuuCENO87KjY3if1QkQ 密码:ttrt


代码

import jieba
path = 'C:\\Users\\Desktop\\红楼梦.txt'
#根据路径以utf-8的格式读取文件内容
txt = open(path,'r',encoding = 'utf-8').read()
words = jieba.lcut(txt)
#通过结果分析,记录需要排除的一些不是人名的名词
excludes = ['这会子','怎么样','为什么','周瑞家',
            '贾母笑','悄悄的','大学生','小说网','电子书']
#定义空的词典类型
counts = {}
for word in words:
    if len(word) == 1 or len(word) == 2:
        continue
    else:
        counts[word] = counts.get(word,0) + 1
for word in excludes:
    del counts[word]
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))

结果显示(结果需要我们修改excludes,然后进行多次的迭代)

猜你喜欢

转载自blog.csdn.net/Mzjuser/article/details/82531581