Python利用WordCount实现词云

版权声明:所爱隔山海。 https://blog.csdn.net/tongxinzhazha/article/details/78596928

前言

构造词云的方法很多,python提供了一个方便的WordCount库来实现了词云以及数据可视化的方法,我们可以方便的得到以下的结果。
参考文档:
GitHub–WordCount文档
- 关键词的视觉化描述;
- 图形可视化,标签化。
- 用于汇总用户生成的标签或一个网站的文字内容; 重要程度能通过改变字体大小或颜色来表现
- 大多数标签本身就是超级链接,直接指向与标签相联的一系列条目。

附:
提供安装各种三方库的方法
1 安装pip
参考网址 https://www.cnblogs.com/NanShan2016/p/5518235.html
2 下载 python 三方库 .whl文件
https://www.lfd.uci.edu/~gohlke/pythonlibs/
并将文件放置在Scripts目录下
3 dos界面
Scripts目录下
pip install wheel
pip install xxx.whl

基础词云的产生Minimal Example

# 导入相关的库
from os import path
import matplotlib.pyplot as plt
from wordcloud import WordCloud

# 获取当前文件路径
d = path.dirname('.')
# path.dirname(__file__) 可以输出该脚本的完整路径,在ide中运行此行会报错


# Read the whole text.
# os.path.join(当下路径,文件名字) 作用是将路径和文件名合成一个路径,适合源代码和元数据放置一起
text = open(path.join(d, 'wordcount_test.txt')).read()

# 若文件另外放置,则看可以直接Open到它的路径
text = open('F:/wordcount_test.txt',"r").read()

# Generate a word cloud image
wc = WordCloud().generate(text)

# 绘图
# matplotlib.pyplot.imshow(X, cmap=None)
# X:图片   cmap:颜色图谱,默认绘制RGB颜色空间
plt.imshow(wc)

# 不显示坐标尺寸
plt.axis("off")
# 显示窗口,只有窗口关闭才执行后续的工作
plt.show()

# 保存图片
wc.to_file("test_1.png")   #存储在源代码处
wc.to_file("F:/python/test_soures/test_2.png")

这里写图片描述

Image-colored wordcloud

采用基于图像的着色策略为词云着色,通过图片词云形状


from os import path
from scipy.misc import imread
import matplotlib.pyplot as plt
from wordcloud import WordCloud,STOPWORDS,ImageColorGenerator


# Read the path
d = path.dirname('.')

# Read the whole text.
# os.path.join(当下路径,文件名字) 作用是将路径和文件名合成一个路径,适合源代码和元数据放置一起
text = open(path.join(d, 'wordcount_test.txt')).read()

# 若文件另外放置,则看可以直接Open到它的路径
text = open('F:/wordcount_test.txt',"r").read()

# 加载背景图片
RGB_coloring = imread(path.join(d, 'F:/python/111.jpg'))
# 设置参数:背景颜色,词云显示的最大词数,设置背景图片,字体最大值
wc = WordCloud(background_color="white",  # 设置词云背影色,
               mask=RGB_coloring,         # 设置词云轮廓
               max_words=2000,            # 设置最大现实的字数
               stopwords=STOPWORDS.add("said"),  
               # 设置停用词,就是屏蔽的词
               max_font_size=40,       # 设置字体最大值
               random_state=42)                  
               # 设置有多少种随机生成状态,即有多少种配色方案

# generate word cloud 产生词云
wc.generate(text)

# 输出原图
plt.figure(0)
plt.imshow(RGB_coloring)
plt.axis("off")
plt.show()

# 绘制一号词云
plt.figure(1)   # plt.figure() 多图标号
plt.imshow(wc)
plt.axis("off")
plt.show()

# 绘制2号词云
# 从背景图片生成颜色值 create coloring from image
image_colors = ImageColorGenerator(RGB_coloring)
# give color_func=image_colors directly in the constructor to recolor wordcloud

plt.figure(2)
plt.imshow(wc.recolor(color_func=image_colors))
plt.axis("off")
plt.show()

输出结果:
这里写图片描述

这里写图片描述

这里写图片描述

猜你喜欢

转载自blog.csdn.net/tongxinzhazha/article/details/78596928