统计关键字生成词云python代码

# coding=utf-8
# Author:XiaoBing
# Date:2021/3/29 21:19
import jieba #分词
from matplotlib import pyplot as  plt #绘图,数据可视化
from wordcloud import WordCloud #词云
from PIL import Image  #图片处理
import numpy as  np #矩阵运算
import sqlite3 #数据库

class word_count:
    def __init__(self,file_path,img_path,final_imgpath):
        self.file_path = file_path
        self.img_path = img_path
        self.final_imgpath = final_imgpath

# 准备词云所需要的文字
    def word_cloud(self):
        with open(self.file_path,mode='r',encoding='utf-8') as f:
            text = ''
            data = f.readlines()
            for item in data:
                text += item
            # print(text)

        # con = sqlite3.connect('movie.db')
        # cur = con.cursor()
        # sql = 'select instroduction from movie250'
        # data = cur.execute(sql)

        # text = ''
        # for item in data:
        #     text = text + item[0]

        # print(text)
        # cur.close()
        # con.close()

        # 分词
        cut = jieba.cut(text)
        string = ' '.join(cut)

        # 图片处理
        img = Image.open(self.img_path)
        img_array = np.array(img) #将图片转换为数组
        # 按照什么格式规则呈现--封装一个对象
        wc = WordCloud(
            background_color=  'white',
            mask = img_array,
            font_path = 'msyh.ttc'#字体位置在:c\windows\fonts
        )
        wc.generate_from_text(string)

        # 绘制图片
        fig = plt.figure(1)
        plt.imshow(wc)
        plt.axis('off') #是否显示坐标轴
        #plt.show() #显示生成的词云图片

        # 输出词云图片
        plt.savefig(self.final_path,dpi = 300) #保存路径+像素


if __name__ == '__main__':
    wc = word_count(
        file_path=r'C:\Users\小冰\Desktop\十四五规划.txt',
        img_path=r'C:\Users\小冰\Desktop\tree.jpg',
        final_imgpath=r'C:\Users\小冰\Desktop\tree1.jpg'
    )
    wc.word_cloud()

从这里到这里~~~~~~
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XB_tonticc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值