Python matplotlib库的应用(根据“荆州”在《三国演义》每一回中出现的次数,绘制折线图)

前提:有完整的《三国演义》电子文本

在另一篇博客中,介绍过爬取《三国演义》、统计武将出现次数、生成词云的操作----<<传送门
这篇将继续,拆分章回并统计“荆州”在每一章的出现次数,使用matplotlib库绘制折线图

结果:
在这里插入图片描述

相关依赖

import matplotlib.pyplot as plt
import re

章回拆分
返回每一章开始与结束的索引构成的列表

def getChapterindex(targettext):
    lst_chapter = []
    #利用正则表达式,找到每一回的位置
    chapter = re.findall("第[\u4E00-\u9FA5]+回", targettext)
    # 为了防止掺杂,进行一遍过滤
    for x in chapter:
        if x not in lst_chapter and len(x) <= 7:
            lst_chapter.append(x)
    # 每一回开始索引
    lst_start_chapterindex = []
    for x in lst_chapter:
        lst_start_chapterindex.append(targettext.index(x))
    # 存放每一回结束索引
    lst_end_chapterindex = lst_start_chapterindex[1:]+[len(targettext)]
    lst_chapterindex = list(zip(lst_start_chapterindex, lst_end_chapterindex))
    return lst_chapterindex

统计每一回荆州出现次数

def countJz(chapterIndex, targettext):
    count = []
    for i in range(120):
        start = chapterIndex[i][0]
        end = chapterIndex[i][1]
        count.append(targettext[start:end].count('荆州'))
    return count

绘制折线图
初步观察,x轴最大刻度值是y轴的三倍,所以设置图像的宽为高的三倍

def draw(count,targetpath):
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.figure(figsize=(15,5))
    plt.plot(count)
    plt.xlabel('章节数')
    plt.ylabel('提及次数')
    plt.legend(labels=['荆州提及次数'])
    plt.title('《三国演义》之战略要地荆州')
    plt.savefig(targetpath.split('.')[0]+'_荆州.png')

以下将放到main()函数里

target_name = '三国演义.txt'  # 目标文件名
target_path = getFile_path(target_name)

target_text = getTarget_text(target_path)

chapter_index= getChapterindex(target_text)
count_Jz = countJz(chapter_index, target_text)
draw(count_Jz,target_path)

如有错误,欢迎私信纠正
技术永无止境,谢谢支持!

猜你喜欢

转载自blog.csdn.net/pineapple_C/article/details/107136706
今日推荐