Python简单的枫叶形状的词云图

您所在的位置:网站首页 python绘制词云图素材 Python简单的枫叶形状的词云图

Python简单的枫叶形状的词云图

2023-03-21 15:12| 来源: 网络整理| 查看: 265

Python有很多词云库,其中比较流行的有wordcloud和pytagcloud。这里我们以wordcloud为例,可通过以下代码安装该库:

pip install wordcloud 1提取文本数据

词云图的数据来源是文本,因此我们需要从文本数据中提取需要展示的关键词。可以从网络上爬取数据,也可以使用本地存储的数据。在这里,我们以本地数据为例,将文本存储在txt文件中,使用Python读取txt文件:

with open('text.txt', 'r', encoding='utf-8') as f: text = f.read() 2数据预处理

在生成词云图前,需要对文本数据进行预处理,如去除无用的停用词、标点符号等。可以使用Python的nltk库进行文本预处理。这里以去除停用词为例:

import nltk nltk.download('stopwords') from nltk.corpus import stopwords stop_words = set(stopwords.words('english')) text = ' '.join([word for word in text.split() if word.lower() not in stop_words]) 3生成词云图

使用WordCloud库的WordCloud()函数生成词云图。其中,可以设置词云图的各项参数,如字体、背景颜色、最大词汇数等。

from wordcloud import WordCloud wordcloud = WordCloud(font_path='msyh.ttc', background_color='white', max_words=100, max_font_size=50) wordcloud.generate(text) import matplotlib.pyplot as plt plt.figure(figsize=(10, 6)) plt.imshow(wordcloud) plt.axis('off') plt.show()

至此,一个简单的词云图生成完成。可以根据需要调整各项参数,使生成的词云图更加美观、准确。

使用枫叶图形绘画词云图实例:

from wordcloud import WordCloud import numpy as np from PIL import Image from matplotlib import colors import collections #这些都是需要使用的库 # -*- coding: utf-8 -*- import jieba from wordcloud import WordCloud import numpy as np from PIL import Image from matplotlib import colors import collections def chinese_jieba(): # 读取目标文本,绘画词云图的文本文件 with open(r'comments.txt', encoding='utf-8') as fp: txt = fp.read() fp.close() wordlist_jieba = jieba.lcut(txt) # 将文本分割,返回列表 txt_jieba = " ".join(wordlist_jieba) # 将列表拼接为以空格为间断的字符串 return txt_jieba def stopwords_read(): # 读取停用词,也可自己根据需求写入 stopwords_ = ['里', '拍'] with open(r'stop.txt', 'r', encoding='utf-8') as f: for line in f: if len(line) > 0: stopwords_.append(line.strip()) return stopwords_ def wordcloud_generate(): stopwords_ = stopwords_read()#读取停用词 txt = chinese_jieba()#读取文本 background_image = np.array(Image.open(r'枫叶形状图片.png'))#自定义背景轮廓 colormaps = colors.ListedColormap(['#871A84', '#BC0F6A', '#BC0F60', '#CC5F6A', '#AC1F4A']) # 自定义字体色,该系列是蓝紫色 wordcloud = WordCloud(font_path='simhei.ttf', # 字体 prefer_horizontal=0.99,#大部分都是横向排放 background_color='white', # 背景色 max_words=100, # 显示单词数 max_font_size=400, #最大字号 stopwords=stopwords_, # 过滤噪声词 mask=background_image,#背景轮廓 colormap=colormaps,#使用自定义颜色 collocations=False ).generate(txt) image = wordcloud.to_image() image.show() # 展示图片 wordcloud.to_file('词云图.jpg') # 保存图片 if __name__ == '__main__': wordcloud_generate()



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3