python实现简单的词云制作程序

需要安装的包:

tkinter pickle wordcloud pylab matplotlib jieba PIL numpy os imageio
(ps:若包未安装,请使用pip install package_name进行包的安装.)

最为核心的函数详解:WorldCloud函数

wc = WordCloud(background_color="white",random_state =2,scale=1,mask=alice_coloring,stopwords=stopwords,collocations=False, font_path=myfont, width=1400, height=1400, margin=2)

关于WorldCloud函数的简单讲解:

1. background_color来改变背景颜色,只实验了white和black其他未验证.
2. 使用scale来改变词云图像的精细度(数值越大越精细也越耗时;>8可能要长达数分钟(测试集为10w字的说说)
3. 使用font_path = myfont来改变词云的字体(汉语词云必须依赖自定义的字体库)
4. min_font_size最小字体大小(默认是4)
5. contour_width词云轮廓的描绘,默认是0不描绘
6.关于WorldCloud函数的详解在文章的最后

词云生成的核心代码:

def wordcloud(d,str1,str2):
    alice_coloring = np.array(Image.open(path.join(d,str2)))#背景图片
    stopwords=set(STOPWORDS)
    stopwords.add("said")
    image_colors = ImageColorGenerator(alice_coloring)
    myfont = (r'tyj.ttf') 
    wc = WordCloud(background_color="white",random_state =2,scale=1,mask=alice_coloring,stopwords=stopwords,collocations=False, font_path=myfont, width=1400, height=1400, margin=2)
    txt = open(path.join(d,str1),encoding='utf-8').read()
    txt_jieba = jieba.cut(txt,cut_all = True)
    txt_finish = " ".join(txt_jieba)

    wc.generate(txt_finish)
    plt.imshow(alice_coloring)
    plt.imshow(wc)
    plt.axis("off")
    plt.show()
    wc.to_file(path.join("名称.jpg"))
wordcloud(d,txt,picture

完整代码:

import tkinter.messagebox
import pickle
from wordcloud import WordCloud ,STOPWORDS, ImageColorGenerator
from pylab import matplotlib,mpl
from matplotlib.font_manager import FontManager
import matplotlib.pyplot as plt
import matplotlib
import jieba
from PIL import Image
import numpy as np
from os import path
from imageio import *
 
window = tk.Tk()
 
window.title('WordCloud Demo Application')
 
window.geometry('400x300')  # 这里的乘是小x
 
canvas = tk.Canvas(window, width=400, height=135, bg='green')
image_file = tk.PhotoImage(file='pic.gif')
image = canvas.create_image(200, 0, anchor='n', image=image_file)
canvas.pack(side='top')
tk.Label(window, text='Welcome',font=('Arial', 16)).pack()
 
tk.Label(window, text='Txt_Input    ', font=('Arial', 14)).place(x=10, y=170)
tk.Label(window, text='Picture_Input', font=('Arial', 14)).place(x=10, y=210)
 
var_txt = tk.StringVar()
var_txt.set('1.txt')
entry_txt = tk.Entry(window, textvariable=var_txt, font=('Arial', 14))
entry_txt.place(x=130,y=175)
var_picture = tk.StringVar()
var_picture.set('love.png')
entry_picture = tk.Entry(window, textvariable=var_picture, font=('Arial', 14))
entry_picture.place(x=130,y=215)

d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()#这部没有明白,是从官方文档中抄过来的

def submit():
    
    # 这两行代码就是获取用户输入的txt和picture
    txt = var_txt.get()
    picture = var_picture.get()
    print(txt,picture)
    def wordcloud(d,str1,str2):
        alice_coloring = np.array(Image.open(path.join(d,str2)))#背景图片
        stopwords=set(STOPWORDS)
        stopwords.add("said")
        image_colors = ImageColorGenerator(alice_coloring)

        myfont = (r'tyj.ttf') 
        wc = WordCloud(background_color="white",random_state =2,scale=1,mask=alice_coloring,stopwords=stopwords,collocations=False, font_path=myfont, width=1400, height=1400, margin=2)
        txt = open(path.join(d,str1),encoding='utf-8').read()
        txt_jieba = jieba.cut(txt,cut_all = True)
        txt_finish = " ".join(txt_jieba)

        wc.generate(txt_finish)
        plt.imshow(alice_coloring)
        plt.imshow(wc)
        plt.axis("off")
        plt.show()
        wc.to_file(path.join("名称.jpg"))
    wordcloud(d,txt,picture)
btn_login = tk.Button(window, text='Submit', command=submit)
btn_login.place(x=190, y=240)
window.mainloop()

使用说明

纯用户的使用说明

  1. 在安装好相应的开发环境和扩展包之后, 并确认你也已经可以成功的运行hello_world.py程序.
    1.1.在此基础上,将全部代码复制粘贴到你的hello_world.py文件中解释并运行.若能出现如下的图片则表示运行成功
    程序解释成功的图片.png

    1.2这时候需要将您希望制作的文档和图片放在和.py文件的文件夹中;在txt_input和picture_input中输入你的文档名称和图片名称(名称都需要带.txt和.png,目前只支持这两种格式)
    1.3点击submit并耐心等待1~2min程序给出词云.
    程序执行过程中的图.png

    放大后的图像.png

    原图.png

    1.4关于python小白制作词云,我建议去一下两个网站免费网站:图悦, 收费网站:易词云. 如果你坚持要使用这个程序,并且觉得花费时间是值得的,那我只能说咱们私聊;邮件请发hangyuntang@gmail.com.个人感觉易词云的功能比这个库函数的功能只多不少.

程序员的使用指南

  1. 参阅github网站https://github.com/amueller/word_cloud
  2. 与我交流hangyuntang@qq.com(只回复技术交流贴,别问我怎么用)

关于WorldCloud函数的详解:

font_path : string

Font path to the font that will be used (OTF or TTF).
Defaults to DroidSansMono path on a Linux machine. If you are on
another OS or don't have this font, you need to adjust this path.
将使用的字体的字体路径(OTF或TTF)。
默认为Linux机器上的DroidSansMono路径。如果你在
另一个操作系统或没有此字体,您需要调整此路径。


width : int (default=400)

Width of the canvas.
画布的宽度 默认是400


height : int (default=200)

Height of the canvas.
画布的高度 默认是200


prefer_horizontal : float (default=0.90)

The ratio of times to try horizontal fitting as opposed to vertical.
If prefer_horizontal < 1, the algorithm will try rotating the word
if it doesn't fit. (There is currently no built-in way to get only
vertical words.)
尝试水平拟合该词(画布中有些词是歪的的始作俑者),>1就尽量使词语水平;默认0.9.


mask : nd-array or None (default=None)

If not None, gives a binary mask on where to draw words. If mask is not
None, width and height will be ignored and the shape of mask will be
used instead. All white (#FF or #FFFFFF) entries will be considerd
"masked out" while other entries will be free to draw on. [This
changed in the most recent version!]
面具是用来设置词云的底图的,注意透明的底图会无法识别.


contour_width: float (default=0)

If mask is not None and contour_width > 0, draw the mask contour.
如果mask不是none并且contour_width>0会描述词云的轮廓,默认为0不描绘轮廓


contour_color: color value (default="black")

Mask contour color.
轮廓的颜色,默认是黑色


scale : float (default=1)

Scaling between computation and drawing. For large word-cloud images,
using scale instead of larger canvas size is significantly faster, but
might lead to a coarser fit for the words.
精细度设置(越打越精细,速度越慢)


min_font_size : int (default=4)

Smallest font size to use. Will stop when there is no more room in this
size.
最小字体


font_step : int (default=1)

Step size for the font. font_step > 1 might speed up computation but
give a worse fit.
字体增长的步长


max_words : number (default=200)

The maximum number of words.
最大的单词数


stopwords : set of strings or None

The words that will be eliminated. If None, the build-in STOPWORDS
list will be used. Ignored if using generate_from_frequencies.
停用字
字符串集或无将要消除的话。如果为None,则内置STOPWORDS
列表将被使用。如果使用generate_from_frequencies则忽略。
笔者也不知道这玩意儿干什么用的

background_color : color value (default="black")

Background color for the word cloud image.
背景色:默认黑


max_font_size : int or None (default=None)

Maximum font size for the largest word. If None, height of the image is
used.
最大的字体大小


mode : string (default="RGB")

Transparent background will be generated when mode is "RGBA" and background_color is None.
无背景色,模式选择为RGBA时将生成透明背景


relative_scaling : float (default='auto')

Importance of relative word frequencies for font-size. With
relative_scaling=0, only word-ranks are considered. With
relative_scaling=1, a word that is twice as frequent will have twice
the size. If you want to consider the word frequencies and not only
their rank, relative_scaling around .5 often looks good.
If 'auto' it will be set to 0.5 unless repeat is true, in which
case it will be set to 0.
.. versionchanged: 2.0
Default is now 'auto'.
字出现的频率和它尺寸的相关程度。�若为relative_scaling = 0,则只考虑单词排名(单词出现次数与字体大小无关)。
若为relative_scaling = 1,则单词的大小与出现次数全相关。如果你想考虑单词频率而不仅仅是他们的排名,相对于.5左右,通常看起来不错。如果'auto',它将被设置为0.5,除非repeat为true,其中case它将被设置为0。.. versionchanged:2.0默认现在是“自动”。


color_func : callable, default=None

Callable with parameters word, font_size, position, orientation,
font_path, random_state that returns a PIL color for each word.
Overwrites "colormap".
See colormap for specifying a matplotlib colormap instead.
To create a word cloud with a single color, use
color_func=lambda *args, **kwargs: "white".
The single color can also be specified using RGB code. For example
color_func=lambda *args, **kwargs: (255,0,0) sets color to red.
regexp : string or None (optional)
Regular expression to split the input text into tokens in process_text.
If None is specified, r"\w[\w']+" is used. Ignored if using
generate_from_frequencies.
每个词的色彩映射:
可以使用参数word,font_size,position,orientation,
font_path,random_state,返回每个单词的PIL颜色。覆盖“色彩映射”。
请参阅colormap以指定matplotlib色彩映射。
要创建单色的文字云,请使用color_func = lambda * args,** kwargs:“white”。也可以使用RGB代码指定单色。例如color_func = lambda * args,** kwargs:(255,0,0)将颜色设置为红色。
regexp:string或None(可选)正则表达式将输入文本拆分为process_text中的标记。如果指定None,则使用r“\ w [\ w'] +”
collocations : bool, default=True
Whether to include collocations
(bigrams) of two words. Ignored if using
generate_from_frequencies.
是否搭配两个字(组成词组),如果使用频率省成法可忽略此项
(笔者猜测是英语的专用形式,汉语应该没啥用)

来自 https://github.com/amueller/word_cloud/blob/master/wordcloud/wordcloud.py
https://github.com/amueller/word_cloud


复现程序功能需要用到的素材

love.png

pic.gif

文本数据 和字体数据移步百度云盘进行下载:
链接: https://pan.baidu.com/s/14Q6Gt6GCjPcC3uYd5VrpNQ 提取码: pihb

致谢和引用

  1. 引用了简书和CSDN三位作者的代码;但是我忘了他们的原文链接了,如有冒犯,我会进行覆写.
  2. 如果原作者想要被挂表扬墙,我一定会乐意效劳的
  3. 主引还是tkinter的官方开发文档和wordcloud的github文档
ps: 1.本文为学生习作,应用于商业的行为是不被允许的. 2.欢迎讨论词云制作的具体细节以及GUI制作和网络编程的实践. 3.作者的最终目标是做一个免费易用但是比图悦功能更丰富的网络词云制作程序.
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,841评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,415评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,904评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,051评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,055评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,255评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,729评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,377评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,517评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,420评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,467评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,144评论 3 317
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,735评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,812评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,029评论 1 256
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,528评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,126评论 2 341

推荐阅读更多精彩内容