python生成自定义形态词云,语义分割完美

python生成词云

介绍

使用python生成自己需要的词云,词云形状可以根据图片自定义
完整地址点击跳转

软件架构

PyCharm 2021.2.3 (Professional Edition)
内部版本号 #PY-212.5457.59,October 19, 2021 构建
运行时版本: 11.0.12+7-b1504.40 x86_64
VM: OpenJDK 64-Bit Server VM,JetBrains s.r.o.
macOS 12.1

安装教程

下载压缩包,解压后整个导入编译器中

使用说明
  1. 下载所需要的拓展库(依次输入下载语句)

    pip install wordcloud

    pip install jieba

  2. # setting paths
    fname_text = 'texts/article.txt' 		        #你需要生成词云的文件地址
    fname_stop = 'hit_stopwords.txt'  	            #分词文件地址,不能动
    fname_mask = 'owl.jpeg'							#生成词云所用的背景地址
    fname_font = 'simhei.ttf'						#生成词云文字的字体地址,可更改自己需要的字体
    
完整代码
import numpy as np
from wordcloud import WordCloud, ImageColorGenerator  # , STOPWORDS
import matplotlib.pyplot as plt
from PIL import Image
import jieba  # cutting Chinese sentences into words


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 ax


def count_frequencies(word_list):
	freq = dict()
	for w in word_list:
		if w not in freq.keys():
			freq[w] = 1
		else:
			freq[w] += 1
	return freq


if __name__ == '__main__':
	# setting paths
	fname_text = '商务英语特征与翻译难点探讨.txt'
	fname_stop = 'hit_stopwords.txt'
	fname_mask = 'touxiang.JPG'
	fname_font = 'simhei.ttf'
	
	# read in texts (an article)
	text = open(fname_text, encoding='utf8').read()
	# Chinese stop words
	STOPWORDS_CH = open(fname_stop, encoding='utf8').read().split()
	
	# processing texts: cutting words, removing stop-words and single-charactors
	word_list = [
		w for w in jieba.cut(text)
		if w not in set(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 cloud
	wcd = WordCloud(font_path=fname_font,  # font for Chinese charactors
	                background_color='white',
	                mode="RGBA",
	                mask=im_mask,
	                )
	# wcd.generate(text) # for English words
	wcd.generate_from_frequencies(freq)
	wcd.recolor(color_func=im_colors)
	
	# visualization
	ax = plt_imshow(wcd, )
	ax.figure.savefig(f'single_wcd.png', bbox_inches='tight', dpi=150)
	
	fig, axs = plt.subplots(1, 2)
	plt_imshow(im_mask, axs[0], show=False)
	plt_imshow(wcd, axs[1])
	fig.savefig(f'conbined_wcd.png', bbox_inches='tight', dpi=150)



参与贡献者
  1. Cynthxxx
  2. 灿烂
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

太阳城S

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

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

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

打赏作者

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

抵扣说明:

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

余额充值