鱼C论坛

 找回密码
 立即注册
查看: 3312|回复: 1

[技术交流] Python 制作简单的词云

[复制链接]
发表于 2021-10-3 09:02:29 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
背景图

                               
登录/注册后可看大图

效果图

                               
登录/注册后可看大图

代码
  1. from os import path
  2. import jieba
  3. from wordcloud import WordCloud
  4. from PIL import Image
  5. import numpy as np
  6. import matplotlib.pyplot as plt


  7. def handle_data():
  8.     """
  9.     处理文本数据
  10.     :return:
  11.     """
  12.     # 读取数据
  13.     with open("data.txt", "r") as f:
  14.         txt = f.read()

  15.     # 去除无效数据
  16.     re_move = [",", "。", " ", '\n', '\xa0']
  17.     for i in re_move:
  18.         txt = txt.replace(i, " ")

  19.     # 使用精确分词模式
  20.     word = jieba.lcut(txt)

  21.     # 保存数据
  22.     with open("data_handled.txt", 'w') as file:
  23.         for i in word:
  24.             file.write(str(i) + ' ')


  25. def generate_image():
  26.     """
  27.     生成图片
  28.     :return:
  29.     """
  30.     # 读取数据
  31.     with open("data_handled.txt", "r") as file:
  32.         txt = file.read()

  33.     # 图片路径
  34.     d = path.dirname(__file__)

  35.     # 生成mask
  36.     mask = np.array(Image.open(path.join(d, "mask.jpg")))

  37.     # 生成word
  38.     word = WordCloud(
  39.         background_color="white",
  40.         width=800,
  41.         height=800,
  42.         mask=mask,
  43.         # 字体路径,WordCloud默认不支持中文,这里的SimHei.ttf需要下载放到系统字体库目录下
  44.         font_path='SimHei.ttf'
  45.     ).generate(txt)

  46.     # 保存图片
  47.     word.to_file('world_cloud.png')

  48.     # 使用plt库显示图片
  49.     plt.imshow(word)

  50.     plt.axis("off")

  51.     plt.show()


  52. if __name__ == '__main__':
  53.     handle_data()
  54.     generate_image()

复制代码


|原文链接:https://juejin.cn/post/7008833196750012452

                               
登录/注册后可看大图
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-6-23 14:06:11 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-22 23:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表