Python使用词云图展示

2023-10-02  本文已影响0人  Ritchie_Li

网上看到一个txt文本信息,共2351条饭否记录,据说是微信之父每天发的饭否记录,其实我不知道什么是饭否。我读取这个文本内容,展示到词语图上。之前也使用过,但是好久没有玩Python了,称假期空闲,练习练习。开始发行“通过网页”变成了高频词汇,一看源文本文件,发行每条记录的后面都包含“ 2010-11-26 13:59 通过网页”,这样通过网页肯定是高频词了,所有重新处理了源文本信息,使用正则表达式式,提前时间节点前的任意字符。使用的正则表达式:.+(?=(\d{4}\-\d{2}\-\d{2}))

提前信息如下:

找一个背景,网上找奋斗图片,去掉背景色,裁剪人物。

完整代码:

from osimport path

from PILimport Image

import numpyas np

import matplotlib.pyplotas plt

import os

import chardet

from wordcloudimport WordCloud, STOPWORDS

# get data directory (using getcwd() is needed to support running example in generated IPython notebook)

d = path.dirname(__file__)if "__file__" in locals()else os.getcwd()

print(d)

# Read the whole text.

# text = open(path.join(d, 'ZXL.txt'), encoding='utf-8', errors='ignore').read()

with open(path.join(d, 'ZXL.txt'), 'rb')as f:

raw_data = f.read()

result = chardet.detect(raw_data)

use_encoding = result['encoding']

# 查看文本使用的编码

print(use_encoding)# utf-8

text =open(path.join(d, 'ZXL.txt'), 'r', encoding=use_encoding).read()

# read the mask image

fight_mask = np.array(Image.open(path.join(d, "fight.png")))

# 指定字体文件路径

font_path =r'C:\Windows\Fonts\方正粗黑宋简体.ttf'

# 创建词云图对象并设置字体

stopwords =set(STOPWORDS)

wc = WordCloud(background_color="white",

              max_words=6000, mask=fight_mask,

              font_path=font_path,

              stopwords=stopwords,

              contour_width=3,

              contour_color='steelblue')

# generate word cloud

wc.generate(text)

# store to file

wc.to_file(path.join(d, "ZXL_example.png"))

# show

plt.imshow(wc, interpolation='bilinear')

plt.axis("off")

plt.show()

运行效果如下:

生产图片文件:

上一篇下一篇

猜你喜欢

热点阅读