使用pyhanlp创建词云

去年我曾经写过一篇文章Python + wordcloud + jieba 十分钟学会用任意中文文本生成词云(你可能觉得这和wordcloud中官方文档中的中文词云的例子代码很像,不要误会,那个也是我写的)

现在我们可以仿照之前的格式在写一份pyhanlp版本的。

对于wordcloud而言,因为原生支持的英文是自带空格的,所以我们这里需要的是进行分词和去停处理,然后将文本变为我们需要的list格式,输入wordcloud。同时因为文档中可能有新的词汇我们之前并没有发现,所以有必要的话。我们还需要进行添加自定义词典的代码。其代码时非常简单的。

首先对于添加自定义词典我们只需要,引用CustomDictionary类即可,代码如下。

    CustomDictionary = JClass("com.hankcs.hanlp.dictionary.CustomDictionary")for word in userdict_list:CustomDictionary.add(word)

不过为了更好的发现新词我们还是采用一款发现新词比较好的分词器,比如默认的维特比,或者CRF。考虑到之前实验中CRF在默认的命名实体识别条件下,表现并不好,或许维特比才是更好的选择。

    mywordlist = []    HanLP.Config.ShowTermNature = FalseCRFnewSegment = HanLP.newSegment("viterbi")

去停功能同样十分简单,我们还是利用之前在分词中提到的方法,不过这次我们把代码更pythoic一些

        CoreStopWordDictionary = JClass("com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary")text_list = CRFnewSegment.seg(text)CoreStopWordDictionary.apply(text_list)fianlText = [i.word for i in text_list]

而是否采用之前文章中的停词功能则可以自主选择,而处理为wordcloud所需要的格式,我们则直接采用之前的代码即可。最终核心部分代码如下:

CustomDictionary = JClass("com.hankcs.hanlp.dictionary.CustomDictionary")for word in userdict_list:CustomDictionary.add(word)mywordlist = []    HanLP.Config.ShowTermNature = FalseCRFnewSegment = HanLP.newSegment("viterbi")fianlText = []if isUseStopwordsOfHanLP == True:CoreStopWordDictionary = JClass("com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary")text_list = CRFnewSegment.seg(text)CoreStopWordDictionary.apply(text_list)fianlText = [i.word for i in text_list]else:fianlText = list(CRFnewSegment.segment(text))liststr = "/ ".join(fianlText)with open(stopwords_path, encoding='utf-8') as f_stop:f_stop_text = f_stop.read()f_stop_seg_list = f_stop_text.splitlines()for myword in liststr.split('/'):if not (myword.strip() in f_stop_seg_list) and len(myword.strip()) > 1:mywordlist.append(myword)return ' '.join(mywordlist)

最终实例

现在我们得到了最终实例,已经可以运行了,关于该部分,你还可以参考我fork的wordcloud项目,还有相比于此处新的变化。那里提供了一个jieba和pyhanlp合并的版本。

# - * - coding: utf - 8 -*-
"""
create wordcloud with chinese
=======================Wordcloud is a very good tools, but if you want to create
Chinese wordcloud only wordcloud is not enough. The file
shows how to use wordcloud with Chinese. First, you need a
Chinese word segmentation library pyhanlp, pyhanlp is One of
the most powerful natural language processing libraries in Chinese
today, and it's extremely easy to use.You can use 'PIP install pyhanlp'.
To install it. Its level of identity of named entity,word segmentation was better than jieba,
and has more ways to do it
"""from os import path
from scipy.misc import imread
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
from pyhanlp import *
%matplotlib inline# d = path.dirname(__file__)
d = "/home/fonttian/Github/word_cloud/examples"stopwords_path = d + '/wc_cn/stopwords_cn_en.txt'
# Chinese fonts must be set
font_path = d + '/fonts/SourceHanSerif/SourceHanSerifK-Light.otf'# the path to save worldcloud
imgname1 = d + '/wc_cn/LuXun.jpg'
imgname2 = d + '/wc_cn/LuXun_colored.jpg'
# read the mask / color image taken from
back_coloring = imread(path.join(d, d + '/wc_cn/LuXun_color.jpg'))# Read the whole text.
text = open(path.join(d, d + '/wc_cn/CalltoArms.txt')).read()#
userdict_list = ['孔乙己']# The function for processing text with HaanLP
def pyhanlp_processing_txt(text,isUseStopwordsOfHanLP = True):CustomDictionary = JClass("com.hankcs.hanlp.dictionary.CustomDictionary")for word in userdict_list:CustomDictionary.add(word)mywordlist = []    HanLP.Config.ShowTermNature = FalseCRFnewSegment = HanLP.newSegment("viterbi")fianlText = []if isUseStopwordsOfHanLP == True:CoreStopWordDictionary = JClass("com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary")text_list = CRFnewSegment.seg(text)CoreStopWordDictionary.apply(text_list)fianlText = [i.word for i in text_list]else:fianlText = list(CRFnewSegment.segment(text))liststr = "/ ".join(fianlText)with open(stopwords_path, encoding='utf-8') as f_stop:f_stop_text = f_stop.read()f_stop_seg_list = f_stop_text.splitlines()for myword in liststr.split('/'):if not (myword.strip() in f_stop_seg_list) and len(myword.strip()) > 1:mywordlist.append(myword)return ' '.join(mywordlist)wc = WordCloud(font_path=font_path, background_color="white", max_words=2000, mask=back_coloring,max_font_size=100, random_state=42, width=1000, height=860, margin=2,)pyhanlp_processing_txt = pyhanlp_processing_txt(text,isUseStopwordsOfHanLP = True)wc.generate(pyhanlp_processing_txt)# create coloring from image
image_colors_default = ImageColorGenerator(back_coloring)plt.figure()
# recolor wordcloud and show
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()# save wordcloud
wc.to_file(path.join(d, imgname1))# create coloring from image
image_colors_byImg = ImageColorGenerator(back_coloring)# show
# we could also give color_func=image_colors directly in the constructor
plt.imshow(wc.recolor(color_func=image_colors_byImg), interpolation="bilinear")
plt.axis("off")
plt.figure()
plt.imshow(back_coloring, interpolation="bilinear")
plt.axis("off")
plt.show()# save wordcloud
wc.to_file(path.join(d, imgname2))

实例使用pyhanlp创建中文词云相关推荐

  1. python中文词云生成_Python 词云生成

    图片来自网络所谓"词云"就是对网络文本中出现频率较高的"关键词"予以视觉上的突出,形成"关键词云层"或"关键词渲染",从 ...

  2. 封装汉语自然语言处理中的常用方法(附代码:生成中文词云)

    前叙 该文章写作共花费二十分钟,阅读只需要七分钟左右,读完该文章后,你将学会使用少量代码,将中文小说,中文新闻,或者其他任意一段中文文本生成词云图 背景 在进行汉语自然语言处理时候,经常使用的几个方法 ...

  3. python制作中文词云_Python如何生成词云(详解)

    前言 今天教大家用wrodcloud模块来生成词云,我读取了一篇小说并生成了词云,先看一下效果图: 效果图一: 效果图二: 根据效果图分析的还是比较准确的,小说中的主人公就是"程理" ...

  4. 用python实现中文词云完整流程(wordcloud、jieba)

    我们将用python3的第三方库wordcloud来做中文词云.通过对2月3日-2月5日国家卫健委的三天记者会实录做词云分析,一定程度上,我们可以得到三天内舆情动向及官方侧重点的变化. # 第三方库 ...

  5. python学习笔记---中文词云

    python学习笔记–中文词云 提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 发现词云的展示还挺有意思的,比较多的应用场景是给用户打标签,社交软件应用较多.今天随便找了一些文字电影 ...

  6. 词云python灿烈_如何用Python做中文词云?

    打算绘制中文词云图?那你得先学会如何做中文文本分词.跟着我们的教程,一步步用Python来动手实践吧. 需求 在<如何用Python做词云>一文中,我们介绍了英文文本的词云制作方法.大家玩 ...

  7. python——wordcloud生成中文词云

    毕设中期答辩,想展示一下前期数据抓取和聚类的成果,感觉词云这种形式不错,于是简单学习了一下wordcloud. 首先是安装 我是使用pip直接安装的, pip install wordcloud 没有 ...

  8. 使用Python制作中文词云

    使用Python制作中文词云 0 素材 & 库 准备 0.1 文本和图片 0.2 库准备 步骤 1. 准备工作 2. 文本处理 2.1 读取文本 2.2 分词和过滤 2.3 统计词频: 3. ...

  9. python中文词云生成

    一.词云 "词云"就是对网络文本中出现频率较高的"关键词"予以视觉上的突出,形成"关键词云层"或"关键词渲染",从而过滤 ...

最新文章

  1. 网页学名为html文件,什么是HTML
  2. 遇到问题为何该自己动手
  3. 【Paper】2019_Consensus Control of Multiple AUVs Recovery System Under Switching Topologies and Time D
  4. CascadingStyleSheets
  5. 「比人还会聊天」百度PLATO对话机器人开放体验
  6. vue中传值和传引用_vue prop属性传值与传引用示例
  7. linux配置php项目路径,linux下如何修改php.ini路径
  8. TLB的作用及工作原理,如何查看TLB miss?
  9. java代码从服务器拉取到本地,集成到idea报错
  10. OpenShift 4 - Istio-Tutorial (1) 教程说明和准备环境
  11. jsp中接收java的返回值_jsp中request的一些方法返回值
  12. MultiThread
  13. android最新图表框架,Android中绘制图表的开源框架AChartEngine初识
  14. php开源bi,Poli 简单易用的开源 BI 软件使用教程
  15. 通俗易懂的AI算法原理
  16. Au:持续性噪音降噪方法
  17. Word-去掉标题前面的小黑点
  18. 推荐一部烂片《东方华尔街》
  19. LED点阵屏中“鬼影”现象的分析与解决
  20. ac Let‘s Play Curling

热门文章

  1. SpringBoot webmvc项目导出war包并在外部tomcat运行产生的诸多问题以及解决方案
  2. iOS系统 越狱系统还原(平刷)
  3. 解决windows10下面无法抓取charles数据包问题
  4. Spring Boot Redis 入门
  5. 计算机基础知识的最小集合
  6. 知乎高赞回答:裁员、降薪、996...这项能力让你寒冬蓄能
  7. mysqlbinlog -v与-vv --base64-output 与不加的区别
  8. 模拟二:STEMA 考试选择题模拟练习试卷(中级组) 及答案 + 解题后期更新
  9. 模拟一:STEMA 考试选择题模拟练习试卷(初级组)及答案 + 自我解题笔记
  10. 监控系统或者网站服务器的报警及复位,机房监控系统标准和常见故障