使用Python绘制各种方法的词云图

import jieba
from PIL import Image
from wordcloud import WordCloud
import numpy as np
import matplotlib.pyplot as plt

# 我们导入文本内容,并且去除掉一下换行符和空格,代码如下
text = open(r"《冰与火之歌》第1卷权力的游戏.txt",encoding='gbk').read()
text = text.replace('\n',"").replace("\u3000","")

# 我们需要将其分成一个个的词,这个时候就需要用到jieba模块了,代码如下
text_cut = jieba.lcut(text)
# 将分好的词用某个符号分割开连成字符串
text_cut = ' '.join(text_cut)
# 结果当中或许存在着不少我们不需要看的、无关紧要的内容,这个时候就需要用到停用词
stop_words = open(r"baidu_stopwords.txt",encoding='utf-8').read().split("\n")

# # 绘制词云图的核心代码
word_cloud = WordCloud(font_path="simsun.ttc",  # 设置词云字体
                       background_color="white",# 词云图的背景颜色
                       stopwords=stop_words) # 去掉的停词
word_cloud.generate(text_cut)
image = word_cloud.to_image()
image.show()
word_cloud.to_file("1.png")

 这样一张极其简单的词云图算是做好了,当然我们可以给它添加一个背景图片,例如下面这张图片,

 主要需要添加的代码如下所示

background = Image.open(r"5.png")
graph = np.array(background)
word_cloud = WordCloud(font_path="simsun.ttc",  # 设置词云字体
                       background_color="white", # 词云图的背景颜色
                       stopwords=stop_words,
                       mask = graph) # 去掉的停词
word_cloud.generate(text_cut)
image = word_cloud.to_image()
image.show()
word_cloud.to_file("2.png")

 除此之外,还有另外一个模块stylecloud绘制出来的词云图也是非常酷炫的,其中我们主要是用到下面这个函数

stylecloud.gen_stylecloud(text=text_cut,
                          palette='tableau.BlueRed_6', #调色板
                          icon_name='fas fa-apple-alt', #词云图的形状
                          font_path=r'田英章楷书3500字.ttf', #字体风格
                          background_color="white",
                          max_font_size=200, #最大的字号
                          max_words=2000, #可以容纳下的最大单词数量
                          stopwords=True,
                          custom_stopwords=stop_words,
                          output_name='3.png')

 最后我们来看一下如何用Pyecharts模块来进行词云图的绘制,代码如下

from pyecharts import options as opts
from pyecharts.charts import Page, WordCloud
words = [
    ("爵士", 933),
    ("奈德", 784),
    ("国王", 666),
    ("琼恩", 629),
    ("提利昂", 595),
    ("布兰", 547),
    ("父亲", 527),
    ("凯特琳", 525),
    ("兰尼斯特", 510),
    ("史塔克", 480),
    ("艾丽娅", 416)
]
c = (WordCloud()
    .add("", words, word_size_range=[20, 100])
    .set_global_opts(title_opts=opts.TitleOpts(title="基本示例"))
     )
c.render("1.html")

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年11月30日
下一篇 2023年11月30日

相关推荐