Python编程实战:老司机奇技淫巧系列之字符转换成图片
小职 2017-09-09 来源 :网络 阅读 1513 评论 0

摘要:本篇Pyhton编程实践教程将为大家讲解Pyhton编程的知识点,看完这篇文章会让你对Python编程的知识点有更加清晰的理解和运用。

本篇Pyhton编程实践教程将为大家讲解Pyhton编程的知识点,看完这篇文章会让你对Python编程的知识点有更加清晰的理解和运用。

先放效果图:

 Python编程实战:老司机奇技淫巧系列之字符转换成图片

还有这个:

 Python编程实战:老司机奇技淫巧系列之字符转换成图片

Python编程实战:老司机奇技淫巧系列之字符转换成图片

是不是立马逼格满满~

这里用到的是一个有趣的模块,叫wordcloud:

github:     https://github.com/amueller/word_cloud 

官网:       https://amueller.github.io/word_cloud/ 

 

*建议自行通过下载setup.py的方式安装,pip install 不一定能下载成功。

打开,并下载: https://github.com/amueller/word_cloud/archive/master.zip

然后 python setup.py install 

安装其它依赖的模块:

必须安装第一步安装numpy:       https://pypi.python.org/pypi/numpy

          scipy:         https://pypi.python.org/pypi/scipy

         jieba:          https://pypi.python.org/pypi/jieba/

下载whl文件,然后 pip install XXXX.whl

如果出现错误,请参考https://www.cnblogs.com/nice-forever/p/5371906.html

分享一下源码:

#coding:utf-8
#author  //blog.csdn.net/fyuanfena/article/details/52038984
from os import pathfrom scipy.misc import imreadimport matplotlib.pyplot as pltimport jieba

from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

 

stopwords = {}def importStopword(filename=''):

    global stopwords

    f = open(filename, 'r', encoding='utf-8')

    line = f.readline().rstrip()

 

    while line:

        stopwords.setdefault(line, 0)

        stopwords[line] = 1

        line = f.readline().rstrip()

 

    f.close()

def processChinese(text):

    seg_generator = jieba.cut(text)  # 使用jieba分词,也可以不使用

    seg_list = [i for i in seg_generator if i not in stopwords]

 

    seg_list = [i for i in seg_list if i != u' ']

 

    seg_list = r' '.join(seg_list)

 

    return seg_list

 

importStopword(filename='./stopwords.txt')

 

# 获取当前文件路径

# __file__ 为当前文件, 在ide中运行此行会报错,可改为

# d = path.dirname('.')

d = path.dirname(__file__)

 

text = open(path.join(d, u'love.txt'),encoding ='utf-8').read()

#如果是中文

text = processChinese(text)#中文不好分词,使用Jieba分词进行

# read the mask / color image

# 设置背景图片

back_coloring = imread(path.join(d, "./image/love.jpg"))

 

wc = WordCloud( font_path='./font/cabin-sketch.bold.ttf ',                      #设置字体 要是使用汉字就用simhei.ttf

                background_color="white", #背景颜色

                max_words=1000,# 词云显示的最大词数

                mask=back_coloring,#设置背景图片

                max_font_size=80, #字体最大值

                random_state=10,   #42                )# 生成词云, 可以用generate输入全部文本(中文不好分词),也可以我们计算好词频后使用generate_from_frequencies函数wc.generate(text)# wc.generate_from_frequencies(txt_freq)

# txt_freq例子为[('词a', 100),('词b', 90),('词c', 80)]

# 从背景图片生成颜色值

image_colors = ImageColorGenerator(back_coloring)

 

plt.figure()# 以下代码显示图片plt.imshow(wc)

plt.axis("off")

plt.show()# 绘制词云

# 保存图片

wc.to_file(path.join(d, "名1称.png"))

 

官方的samplecode给出的效果图示例:

#!/usr/bin/env python"""

Image-colored wordcloud

=======================

 

You can color a word-cloud by using an image-based coloring strategy

implemented in ImageColorGenerator. It uses the average color of the region

occupied by the word in a source image. You can combine this with masking -

pure-white will be interpreted as 'don't occupy' by the WordCloud object when

passed as mask.

If you want white as a legal color, you can just pass a different image to

"mask", but make sure the image shapes line up."""

from os import pathfrom PIL import Imageimport numpy as npimport matplotlib.pyplot as plt

from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

 

d = path.dirname(__file__)

# Read the whole text.

text = open(path.join(d, 'alice.txt')).read()

# read the mask / color image taken from

# //jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-282261010

alice_coloring = np.array(Image.open(path.join(d, "alice_color.png")))

stopwords = set(STOPWORDS)

stopwords.add("said")

 

wc = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,

               stopwords=stopwords, max_font_size=40, random_state=42)# generate word cloudwc.generate(text)

# create coloring from image

image_colors = ImageColorGenerator(alice_coloring)

# show

plt.imshow(wc, interpolation="bilinear")

plt.axis("off")

plt.figure()# recolor wordcloud and show

# we could also give color_func=image_colors directly in the constructor

plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")

plt.axis("off")

plt.figure()

plt.imshow(alice_coloring, cmap=plt.cm.gray, interpolation="bilinear")

plt.axis("off")

plt.show()

 Python编程实战:老司机奇技淫巧系列之字符转换成图片

Python编程实战:老司机奇技淫巧系列之字符转换成图片

最后感谢  //blog.csdn.net/fyuanfena/article/details/52038984

和ta的项目源码:https://github.com/fyuanfen/wordcloud

以上,关于Pyhton的全部内容讲解完毕啦,欢迎大家继续关注!更多关于Python的干货请关注职坐标Python频道!

本文由 @小职 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 1
看完这篇文章有何感觉?已经有2人表态,50%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程