码迷,mamicode.com
首页 > 编程语言 > 详细

Python 词云 【中/英】小白简单入门教程

时间:2018-08-06 00:34:36      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:content   tar   利用   tps   nump   text   教程   ice   font   

1. 分析

构建词云需要具备:

  • 原料即文章等内容
  • 将内容进行分词
  • 将分词后的内容利用构建词云的工具进行构建
  • 保存成图片

2. 需要的主要模块

  • jieba 中文分词
  • wordcloud 构建词云

3. 模块原理

wordcloud的实现原理

  • 文本预处理
  • 词频统计 
  • 将高频词以图片形式进行彩色渲染

jieba的实现原理

  • 进行中文分词(有多种模式)【详情

4. 英文词云

英文分词和构建词云只需要wordcloud模块

具体实现如下:

 1 from wordcloud import WordCloud
 2  
 3 string = 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.
 4 font = rC:\Windows\Fonts\FZSTK.TTF
 5 wc = WordCloud(font_path=font, #如果是中文必须要添加这个,否则会显示成框框
 6                background_color=white,
 7                width=1000,
 8                height=800,
 9                ).generate(string)
10 wc.to_file(ss.png) #保存图片

5. 中文分词

具体实现如下:

1 import jieba 
2 cut = jieba.cut(text)  #text为你需要分词的字符串/句子
3 string =  .join(cut)  #将分开的词用空格连接

6. 中文词云

中文词云需要jieba和wordcloud模块

具体实现如下:

 1 import jieba
 2 from wordcloud import WordCloud
 3 from PIL import Image
 4 import numpy as np
 5 
 6 font = hwkt.ttf
 7 content = (open(岗位需求.txt,r,encoding=utf-8)).read()
 8 cut = jieba.cut(content)
 9 cut_content =  .join(cut)
10 img = Image.open(22.png) # 以什么图片进行显示
11 img_array = np.array(img) # 将图片转换为数组
12 
13 wc = WordCloud(
14     background_color=white,
15     mask=img_array, # 若没有该项,则生成默认图片
16     font_path=font # 中文分词必须有中文字体设置
17 )
18 wc.generate_from_text(cut_content) # 绘制图片
19 wc.to_file(new.png) # 保存图片

7. 实现效果

英文词云实现效果如下:

技术分享图片

 

中文词云实现效果如下:

 技术分享图片

 

Python 词云 【中/英】小白简单入门教程

标签:content   tar   利用   tps   nump   text   教程   ice   font   

原文地址:https://www.cnblogs.com/littlebob/p/9427896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!