利用pyecharts绘制主题河流图

本文将根据一个文件夹(包括一段时间人民日报的发文以txt格式保存),提取以’党', '发展', '中国', '我们', '人民'五个为主题的随时间变化的词频的变化,用主题河流图直观的展现

import re # 正则表达式库
import collections # 词频统计库
from pyecharts import options as opts
import jieba # 结巴分词
import os
from pyecharts.charts import ThemeRiver
def find_time(yanbao_txt):#定义自定义函数查找时间
    paras = [para.strip() for para in yanbao_txt.split('\n') if para.strip()][:5]
    for para in paras:
        ret = re.findall(r'(\d{4})\s*[\./年-]\s*(\d{1,2})\s*[\./月-]\s*(\d{1,2})\s*日?', para)
        if ret:
            year, month, day = ret[0]
            time = '{}/{}/{}'.format(year, month.lstrip(), day.lstrip())
            return time
    return None    #读取其中的日期
data=[]
# 定义文件夹路径
folder_path = ""  # 替换为你的文件夹路径
# 读取并合并所有txt文件
txts=[]
for file_name in os.listdir(folder_path):
    if file_name.endswith('.txt'):
        file_path = os.path.join(folder_path, file_name)
        with open(file_path, 'r', encoding='utf-8') as f:
                file_content = f.read()
                # 文本预处理
                pattern = re.compile(u'\t|\n|\.|-|:|;|\)|\(|\?|"')  # 定义正则表达式匹配模式
                string_data = re.sub(pattern, '', file_content)  # 将符合模式的字符去除
                # 文本分词
                seg_list_exact = jieba.cut(string_data, cut_all=False)  # 精确模式分词
                object_list = []
                remove_words = [u'的', u',',u'和', u'是',  u'对',u'等',u'能',u'都',u'。',u' ',u'、',u'中',u'在']# 自定义去除词库
                for word in seg_list_exact: # 循环读出每个分词
                    if word not in remove_words: # 如果不在去除词库中
                        object_list.append(word) # 分词追加到列表
                data.append([find_time(file_content), collections.Counter(object_list)["党"], "党"])
                data.append([find_time(file_content), collections.Counter(object_list)["发展"], "发展"])
                data.append([find_time(file_content), collections.Counter(object_list)["中国"], "中国"])
                data.append([find_time(file_content), collections.Counter(object_list)["我们"], "我们"])
                data.append([find_time(file_content), collections.Counter(object_list)["人民"], "人民"])
tr= (
        ThemeRiver(init_opts=opts.InitOpts(width="1300px", height="700px"))
            .add(
            series_name=['党', '发展', '中国', '我们', '人民'],
            data=data,
            singleaxis_opts=opts.SingleAxisOpts(
                pos_top="50", pos_bottom="50", type_="time"
            ),
        )
            .set_global_opts(
            tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line"),
            legend_opts=opts.LegendOpts(pos_left='50%')
        )
        .render("themeriver.html")
    )

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值