python读取txt文件生成词云

提要:
该文章记录用于通过读取txt文件中的内容生成词云

代码:

import os
import jieba
from wordcloud import WordCloud
import imageio

def create():
    with open('noun.txt', 'r', encoding='utf-8') as f:
        text = f.read()
    words = jieba.cut(text)
    words = list(words)
    mask_path = "n.png"
    mask = None
    if os.path.exists(mask_path):
        mask = imageio.v2.imread(mask_path)

    wc = WordCloud(background_color='white', width=1920, height=1040, font_path='msyh.ttc', mask=mask)
    wc.generate(' '.join(words))
    wc.to_file("noun.png")

if __name__ == '__main__':
    create()

说明:

这个生成词云的代码基本上就可以通过这个模板来

with open('noun.txt', 'r', encoding='utf-8') as f:
        text = f.read()

noun.txt是你要读取的文件,通过这段代码读取

	words = jieba.cut(text)
    words = list(words)

这段代码则是通过python的jieba库进行分词操作

	mask_path = "n.png"
    mask = None
    if os.path.exists(mask_path):
        mask = imageio.v2.imread(mask_path)

这段代码用于设置词云的背景图,也就是将词云弄成你自己想要的图案,
n.png就是背景图,但是要注意背景图的要是白底的。
如下图:
1

	wc = WordCloud(background_color='white', width=1920, height=1040, font_path='msyh.ttc', mask=mask)
    wc.generate(' '.join(words))
    wc.to_file("noun.png")

这段代码就是生成词云了,wc.to_file(“noun.png”)这里就是将词云结果保存为名字为noun.png的图片。

运行结果:
2
完成~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

泉绮

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

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

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

打赏作者

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

抵扣说明:

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

余额充值