Last active
September 29, 2019 03:45
-
-
Save zclongpop123/e0f31e97d3a1ec423d474bf1ddf4d54a to your computer and use it in GitHub Desktop.
使用词云生成关键词图片
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
#======================================== | |
# author: Changlong.Zang | |
# mail: zclongpop123@163.com | |
# time: Tue Sep 24 14:54:13 2019 | |
#======================================== | |
import os | |
import numpy | |
import jieba | |
from PIL import Image | |
from wordcloud import WordCloud, color_from_image | |
#--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | |
def main(text_path, input_image_path, output_image_path): | |
''' | |
''' | |
if not os.path.isfile(text_path): | |
return | |
if not os.path.isfile(input_image_path): | |
return | |
#- | |
txt_data = '' | |
with open(text_path) as f: | |
txt_data = f.read() | |
count_data = dict() | |
for w in jieba.cut(txt_data, cut_all=False): | |
if len(w) < 2: | |
continue | |
count_data[w] = count_data.get(w, 0) + 1 | |
image_mask = numpy.array(Image.open(input_image_path)) | |
_wc = WordCloud(font_path='C:/Windows/Fonts/simhei.ttf', mask=image_mask, background_color='white') | |
_wc.generate_from_frequencies(count_data) | |
_wc.recolor(color_func=color_from_image.ImageColorGenerator(image_mask)) | |
_wc.to_file(output_image_path) | |
if __name__ == '__main__': | |
main('D:/aaa.txt', 'D:/aaa.jpg', 'D:/bbb.jpg') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment