下面将分两个章节具体学习wordCloud这个比较火的类。
第一个章节学使用。
第二个章节看源码,解释第一个章节中没有看懂的问题。
Environment:
eclipse+pydev python3
- 1–分析使用方法:
用到的库:WordCloud; matplotlib.pyplot
(1)从txt文件中,读出要分析的文字数据;最好是用空格或者带标点的。这是由WordCloud的分析算法决定的,文件越大,程序越慢。
(2)设定字图的风格,WordCloud给了很多可以设定的参数。会在后面逐个解说。
(3)使用只有两句代码:
wc1 = WordCloud(
background_color="green",
width=1000,
height=860,
font_path="C:/Windows/Fonts/simfang.ttf",margin=2)
wc2 = wc1.generate(text)
在WordCloud()的初始化函数中,设定参数
在generate()函数中做字词分析,最后得到的是一个WordCloud()对象,把它画出来就行了。
- 2–实现案例:
# coding: utf-8
# Description: to use matplotlib learn visuallized
from wordcloud import WordCloud
# 数学绘图类
# 解决:turnning interactive mode on的问题。
import matplotlib.pyplot as plt
def WordCloudExample():
# preparetion: using the word from the file
file = open("D:\\Datas\\word.txt","r")
text = file.read()
#type = chardet.detect(text)
#text1 = text.decode(type["encoding"])
wc1 = WordCloud(
background_color="green",
width=1000,
height=860,
font_path="C:/Windows/Fonts/simfang.ttf",
margin=2)
wc2 = wc1.generate(text)
#resultfile = open("D:\\Datas\\word1.txt","r")
#resulttext = resultfile .read()
plt.axis("off")
plt.imshow(wc2)
plt.show()