python绘制词云图(内附背景图,简单项目易上手)

本项目前期用jieba分词然后用wordcloud绘制词云图
环境python3.8 使用IDE为pycharm

1.需要导入的包

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

2.jieba分词生成词频字典

text=pd.read_csv('tongjifenxi-zhihu.csv')
with open('中文停用词.txt','r', encoding='utf-8') as f:
    #print(f.readlines())
    stopwords=f
    stop=[x.strip() for x in f.readlines()]#
dic={}
for i in text['zhaiyao']:
    for st in [' ',')',',','。','—','、','的','年','为',',']:#针对性去停用词
        i=i.replace(st,'')
    words=jieba.lcut(i)#返回列表
    #print(words)
    for i in words:
        if i in stop:
         words.remove(i)#按元素删除
    #print(words)

    for n in words:
        dic[n]=dic.get(n,0)+1

text的zhaiyao列为纯文本,展示读取text.zhaiyao[0]第一行内容:
在这里插入图片描述
最后处理为:
在这里插入图片描述

3.绘制词云图

img=Image.open(r'rio.png')#打开背景图 自定义
font = r'C:\Windows\Fonts\FZSTK.TTF'
img_array = np.array(img) #将图片装换为数组
wc = WordCloud(
    background_color='white',
    width=1000,
    height=800,
    mask=img_array ,#设置背景图片
    #stopwords=stop,
    font_path=font
)
wc.generate_from_frequencies(dic)
plt.imshow(wc)
plt.axis('off')#隐藏坐标轴
plt.show()  #显示图片

在这里插入图片描述
分享几个底板背景图给大家:
在这里插入图片描述

在这里插入图片描述

  • 7
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要使用Python绘制,可以使用Python第三方库`wordcloud`。这个库可以根据给定的文本数据生成。要生成带有背景片的,可以使用`WordCloud`类的`mask`参数。 以下是一个示例代码,演示如何使用`wordcloud`库生成带有背景片的: ```python from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt from PIL import Image import numpy as np # 读取文本文件 text = open('text.txt', 'r', encoding='utf-8').read() # 读取背景片 background = np.array(Image.open("background.png")) # 创建停用集合 stopwords = set(STOPWORDS) stopwords.add("said") # 创建对象 wc = WordCloud(background_color="white", max_words=2000, mask=background, stopwords=stopwords, contour_width=3, contour_color='steelblue') # 生成 wc.generate(text) # 显示 plt.imshow(wc, interpolation='bilinear') plt.axis("off") plt.show() ``` 在上面的代码中,首先使用`open`函数读取文本文件,然后使用`np.array`函数读取背景片。接着创建停用集合,用于过滤掉一些常见的语,比如“said”。然后创建`WordCloud`对象,设置一些参数,比如背景颜色、最大数、掩膜片、停用等。最后使用`generate`方法生成,使用`imshow`方法显示。 注意,该代码中使用了的默认字体。如果你想更改字体,可以在创建`WordCloud`对象时使用`font_path`参数,指定你想要使用的字体文件路径。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值