Python使用词云图展示

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

提取信息如下:

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

完整代码:

from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import os
import chardet

from wordcloud import 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()


运行效果如下:

生产图片文件:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

flysh05

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

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

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

打赏作者

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

抵扣说明:

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

余额充值