python 操作word 替换字符串为图片_python实战===老司机奇技淫巧系列之字符转换成图片...

先放两张效果图:

还有这个:

是不是立马逼格满满~

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

*建议自行通过下载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 http://blog.csdn.net/fyuanfena/article/details/52038984

from os importpathfrom scipy.misc importimreadimportmatplotlib.pyplot as pltimportjiebafrom wordcloud importWordCloud, STOPWORDS, ImageColorGenerator

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

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

line=f.readline().rstrip()whileline:

stopwords.setdefault(line, 0)

stopwords[line]= 1line=f.readline().rstrip()

f.close()defprocessChinese(text):

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

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

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

seg_list= r' '.join(seg_list)returnseg_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 importpathfrom PIL importImageimportnumpy as npimportmatplotlib.pyplot as pltfrom wordcloud importWordCloud, 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#http://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 cloud

wc.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()

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

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

顺便提一下

如果你也喜欢Python 这里有一群Python爱好者汇集在此。

关注微信公众号:【软件测试技术】,回复 888,获取QQ群号。

Python作为一种高级编程语言,有许多巧妙的设计和特性,被誉为“一种你会喜欢上的语言”(There's a lot you can do with just a few lines of code)。以下是几个Python的独特之处和一些常见的奇技淫巧: 1. **列表推导式 (List Comprehension)**:这是一种简洁的方式来创建新的列表,通常用于数据转换或过滤。例如 `new_list = [x * x for x in range(5)]` 创建了一个包含0到4的平方数的新列表。 2. **生成器 (Generators)**:生成器是惰性求值的序列,它们按需计算值,节省内存。比如 `gen = (x*x for x in range(10))` 可以逐个生成0到9的平方。 3. **装饰器 (Decorators)**:Python允许在运行时修改函数或类的行为,通过定义接收其他函数作为输入并返回新函数的函数,如 `@staticmethod` 和 `@classmethod`。 4. **鸭子类型 (Duck Typing)**:Python并不关心类型的严格匹配,只要对象有需要的方法就认为它是可以的,这使得代码更具灵活性。 5. **元组解包 (Tuple Unpacking)**:可以用变量名直接接收元组或列表的元素,如 `(a, b) = ('Hello', 'World')`。 6. **魔法方法 (Magic Methods)**:特殊的双下划线开头和结尾的方法(如 `__init__`、`__str__`),用于实现自定义操作,如实例化、比较和显示。 7. **异常处理 (Exception Handling)**:Python的try-except-finally结构可以优雅地处理错误,提供了一种控制程序流程的方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值