源程序|使用Python将数据库中的文本生成词云图

使用Python将数据库中的文本生成词云图 一、导入相关第三方库

import jieba # 分词 from PIL import Image # 图片处理 from matplotlib import pyplot as plt # 绘图 数据可视化 from wordcloud import WordCloud # 词云 import numpy as np # 矩阵运算 import sqlite3 # 数据库

二、准备词云所需要的文字(词)
conn = sqlite3.connect('movie250.db') cur = conn.cursor() sql = 'select introduction from movie250' data = https://www.it610.com/article/cur.execute(sql) text =" " for item in data : text = text + item[0] # 将所有文本拼接到一起 # print(item[0]) cur.close() conn.close()

三、进行分词
cut = jieba.cut(text) string = ' '.join(cut) print(len(string))img = Image.open(r'.\static\assets\img\tree.jpg') # 打开遮罩图片 img_array = np.array(img) # 将图片转变成图片数组 wc = WordCloud( background_color='white',# 形成的词云图片背景 mask = img_array , # 遮罩文件为数组 font_path='msyhbd.ttc',#字体 所在位置为C:\Windows\Fonts stopwords = '的' ) wc.generate_from_text(string) # 从文本中选择生成的词云对象

四、绘制图片
fig = plt.figure(1) #从第一个位置开始绘制 plt.imshow(wc)# 按照词云wc的规则显示词云图片 plt.axis('off') #是否显示坐标轴

五、显示生成的词云图片
plt.show()

六、输出词云图到文件
plt.savefig(r'.\static\assets\img\wordcloud.jpg',dpi=500) #dpi=500 设置分别率

【源程序|使用Python将数据库中的文本生成词云图】源程序|使用Python将数据库中的文本生成词云图
文章图片

    推荐阅读