100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 用python做词云 包含:处理词云形状+分词+绘制词云

用python做词云 包含:处理词云形状+分词+绘制词云

时间:2024-02-04 11:13:49

相关推荐

用python做词云 包含:处理词云形状+分词+绘制词云

用python制作词云

包含:处理词云形状+分词+绘制词云

以下代码不超过100行

1、处理词云形状

你可能想把词云做成不同的形状,例如方形、圆形,甚至更复杂的,例如一个人体形状。

首先选一张背景为纯色的图,注意背景色不能跟图形一致。然后将图片的纯色背景转换为透明。

2、分词

需要选择分词词库,意思是按照词库里的字词或符号分隔。打开本文附件的词库,看看是否是自己需要的。

有时你可能不需要太复杂的词库,例如,你现在有很多词语,被顿号隔开,那么可以新建一个txt,仅输入一个顿号。然后将该txt作为分词词库。

3、绘制词云

绘制时有很多参数可以设置。

欢迎读者与我交流~

import numpy as npfrom wordcloud import WordCloud, ImageColorGeneratorimport matplotlib.pyplot as pltfrom PIL import Imageimport jieba # 用于分词def plt_imshow(x, ax=None, show=True):if ax is None:fig, ax = plt.subplots()ax.imshow(x)ax.axis("off")if show: plt.show()return axdef count_frequencies(word_list):freq = dict()for w in word_list:if w not in freq.keys():freq[w] = 1else:freq[w] += 1return freq#你可能想把词云做成不同的形状,例如方形、圆形,甚至更复杂的,例如一个人体形状。#首先选一张背景为纯色的图,注意背景色不能跟图形一致。使用本段代码,将图片的纯色背景转换为透明。#在本例中,是将fang.png这张图的白色背景转为透明。img = Image.open('G:/python_program/ci/pictures/fang.png').convert('RGBA')W, L = img.sizewhite_pixel = (0, 0, 0, 0) # 白色(根据自己的图片的背景色来设置颜色。若背景色跟图形中某部分一致,则会将图形转化,最终的词云图形会不完整。)for h in range(W):for i in range(L):if img.getpixel((h, i)) == white_pixel:img.putpixel((h, i), (255, 255, 255, 0)) # 转换为透明img.save('G:/python_program/ci/fang_new.png') # 自己设置保存地址# In[]#if __name__ == '__main__':# setting pathsfname_text = 'G:/python_program/ci/texts/par.txt'#词云的文本fname_stop = 'G:/python_program/ci/stopwords/hit_stopwords.txt' #选择一个分词词库,程序将根据该词库进行分词。词库见文末附件fname_mask = 'G:/python_program/ci/pictures/fang.png'#用于接下去提取图片的颜色作为词云颜色。自己也可直接选定颜色fname_font = 'G:/python_program/ci/dn.ttf'#'SourceHanSerifK-Light.otf'#选择字体backgroud_image = plt.imread('G:/python_program/ci/pictures/fang_new.png')#关键步骤,读取转换后背景透明的图片# read in texts (an article)text = open(fname_text, encoding='utf8').read()# Chinese stop wordsSTOPWORDS_CH = open(fname_stop, encoding='utf8').read().split()# processing texts: cutting words, removing stop-words and single-charactorsword_list = text# word_list = [# w for w in jieba.cut(text) # have cutted dont use# if w not in STOPWORDS_CH and len(w) > 1# ]freq = count_frequencies(word_list)# processing image im_mask = np.array(Image.open(fname_mask))im_colors = ImageColorGenerator(im_mask)# generate word cloudwcd = WordCloud(font_path=fname_font, # font for Chinese charactorsbackground_color='white',relative_scaling=0.8,mode="RGBA", prefer_horizontal=1,mask=backgroud_image,min_font_size=10)#background_color=None'white',im_maskwcd.generate(text) # for English words#wcd.generate_from_frequencies(freq)# wcd.recolor(color_func = im_colors)# visualizationax = plt_imshow(wcd)ax.figure.savefig('G:/python_program/ci/par.png', bbox_inches='tight', dpi=900)

附件

常用分词词库

1.中文停用词表 cn_stopwords.txt

2.哈工大停用词表 hit_stopwords.txt

3.百度停用词表 baidu_stopwords.txt

4.四川大学机器智能实验室停用词库 scu_stopwords.txt

获取词库方式:

百度网盘链接: /s/1Tj989XLO_OilqepvCfQmrg?pwd=6666

提取码: 6666

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。