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

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 = r'C:\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. 实现效果

英文词云实现效果如下:

中文词云实现效果如下:

 

猜你喜欢

转载自www.cnblogs.com/littlebob/p/9427896.html