python对红楼梦的每一章节进行词频统计

python对红楼梦的每一章节进行词频统计

import jieba
f=open("G:\\红楼梦.txt","r",encoding="utf-8")
txt=f.read()
words=jieba.lcut(txt)#精准模式
ls=[]
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201030001436824.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3RkbDMyMDcyMQ==,size_16,color_FFFFFF,t_70#pic_center)

for word in words:
    a={
    
    }
    if word[0] == "第" and word[-1] == "回":
        if word in ls:
            continue
        else:
            ls.append(word)
print(ls)

for i in range(len(ls)):
    print(ls[i])
    a={
    
    }
    if i<len(ls)-1:
        for word in words[words.index(ls[i])+1:words.index(ls[i + 1])]:
            if len(word) == 1:  # 排除单个字符的统计结果
                continue
            else:
                a[word] = a.get(word, 0) + 1

    elif i ==len(ls)-1:#最后一回

        for word in words[words.index(ls[i])+1:]:
            if len(word) == 1:  # 排除单个字符的统计结果
                continue
            else:
                a[word] = a.get(word, 0) + 1

    items = list(a.items())  # 将字典转换为记录列表
    items.sort(key=lambda x: x[1], reverse=True)  # 记录第二列排序


    for i in range(5):
        word, count = items[i]
        print("{0:<10}{1:>5}".format(word, count))
    print("\n")


f.close()

第一步是打开红楼梦.txt文件,只读的方式,使用UTF-8编码方式
第二步是使用精准模式,将单词保存到words列表中,再将“第几回”存放到一个新的列表中,便于对红楼梦文件每一回进行切片,切边的界点便是第多少回这样的字眼,第一种统计是第i回到第i+1回的之间的词频统计,还有一种就是最后一回的词频统计。
使用一个字典类型a={},统计单词的次数:

for word in words:
    if len(word)==1:#排除单个字符的统计结果
        continue
    else:
        a[word]=a.get(word,0)+1

如果字符长度为1则跳过,否则使用a.get(word,0)方法表示:如果word在a中则返回word对应的值,如果word不在a中就返回0。
第三步是对单词的统计的值从高到低进行排序,输出前5个高频词语,并格式化打印输出。由于字典没有顺序,需要将其转换为有顺序的列表类型,再使用sort()方法和lambda函数配合实现单词出现的次数,对元素进行排序。最后输出排序结果前15位的单词。

items=list(a.items())#将字典转换为记录列表
items.sort(key=lambda x:x[1],reverse=True)#记录第二列排序

运行结果

猜你喜欢

转载自blog.csdn.net/tdl320721/article/details/109376046