jirba库的使用和好玩的词云

1、jieba库基本介绍

  (1)、jieba库概述 

         jieba是优秀的中文分词第三方库 

         中文文本需要通过分词获得单个的词语
         - jieba是优秀的中文分词第三方库,需要额外安装

         - jieba库提供三种分词模式,最简单只需掌握一个函数

  (2)、jieba分词的原理

         Jieba分词依靠中文词库 

         利用一个中文词库,确定汉字之间的关联概率
         - 汉字间概率大的组成词组,形成分词结果

         - 除了分词,用户还可以添加自定义的词组

 

2、jieba库使用说明

  (1)、jieba分词的三种模式 

         精确模式、全模式、搜索引擎模式 

         精确模式:把文本精确的切分开,不存在冗余单词
         - 全模式:把文本中所有可能的词语都扫描出来,有冗余

         - 搜索引擎模式:在精确模式基础上,对长词再次切分

  (2)、jieba库常用函数

  
 
 以下是我的代码:选用文本三体
import  jieba

txt = open("D:\\刘慈欣 - 三体.txt", "r").read()
words = jieba.lcut(txt) 
counts = {}   

for word in words:
    if  len(word)== 1: 
        continue
    else:
        counts[word] = counts.get(word, 0) + 1
        
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)  
for i in range(15):               #输出频率前15的词
    word, count = items[i]
    print("{0:<5}{1:>5}".format(word, count))

效果:

 

 一下是运用词云的代码及效果图
from wordcloud import WordCloud
import matplotlib.pyplot as plt #绘制图像的模块
import jieba     #jieba分词

path_txt='刘慈欣 - 三体.txt'
f = open(path_txt,'r').read()

# 结巴分词,生成字符串,wordcloud无法直接生成正确的中文词云
cut_text = " ".join(jieba.cut(f))

wordcloud = WordCloud(
 #设置字体,不然会出现口字乱码,文字的路径是电脑的字体一般路径,可以换成别的
 font_path="C:/Windows/Fonts/simfang.ttf",
 #设置了背景,宽高
 background_color="white",width=1920,height=1080).generate(cut_text)

plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()

 

 
posted @ 2019-04-03 22:42  呆。  阅读(314)  评论(0编辑  收藏  举报