---恢复内容开始---
运用jieba库分词
一、jieba库基本介绍
1、jieba库概述
jieba是优秀的中文分词第三方库
-中文文本需要通过分词获得单个的词语
-jieba是优秀的中文分词第三方库,需要额外安装
-jieba库提供三种分词模式,最简单只需掌握一个函数
2、jieba分词的原理
jieba分词依靠中文词库
-利用一个中文词库,确定汉字之间的关联概率
-汉字间概率大的组成词组,形成分词结果
-除了分词,用户还可以添加自定义的词组
3、jieba库使用说明
(1)、jieba分词的三种模式
精确模式、全模式、搜索引擎模式
-精确模式:把文本精确的切分开,不存在冗余单词
-全模式:把文本中所有可能的词语都扫描出来,有冗余
-搜索引擎模式:在精确模式基础上,对长词再次切分
(2)、jieba库常用函数
二、安装jieba库
点击电脑中的‘开始’,然后在搜索栏中输入‘cmd’,点击‘命令指示符’,出现界面后在输入‘pip install jieba’,刚开始的时候,我的电脑出现了这样的情况,安装不了。
后来在老师的帮助下,就安装成功了。而且在安装其他库的时候也不会再出现第一次的情况。
这样就安装成功啦~~~
三、jieba库的使用用例
1、分词
2、词云
这是我在网上找的词云的一个例子:
1 # 如果您需要使用此代码,os.chdir路经需要指定到txt文本所在路径
2 # 使用zipin函数,需要txt有read()函数可以打开的正确的编码格式
3 # 使用cipin函数需要安装jieba库
4 # 使用word cloud函数需要安装wordcloud与matplotlib库
5 import os
6 import codecs
7 import jieba
8 import pandas as pd
9 from wordcloud import wordcloud
10 from scipy.misc import imread
11 import matplotlib.pyplot as plt
12 os.chdir("/users/zhaohaibo/desktop")
13
14 class hlm(object):
15
16 # —————————————————————
17 # zipin(self, readdoc, writedoc)
18 # readdoc: 要读取的文件名
19 # writedoc:要写入的文件名
20
21 # output
22 # 字频前100,并写入writedoc
23 # —————————————————————
24 def zipin(self, readdoc, writedoc):
25 word_lst = []
26 word_dict = {}
27 exclude_str = ",。!?、()【】<>《》=:+-*—“”…"
28 with open(readdoc,"r") as filein ,open(writedoc,'w') as fileout:
29
30 # 添加每一个字到列表中
31 for line in filein:
32 for char in line:
33 word_lst.append(char)
34
35 # 用字典统计每个字出现的个数
36 for char in word_lst:
37 if char not in exclude_str:
38 if char.strip() not in word_dict: # strip去除各种空白
39 word_dict[char] = 1
40 else :
41 word_dict[char] += 1
42
43 # 排序x[1]是按字频排序,x[0]则是按字排序
44 lstwords = sorted(word_dict.items(), key=lambda x:x[1], reverse=true)
45
46 # 输出结果 (前100)
47 print ('字符\t字频')
48 print ('=============')
49 for e in lstwords[:100]:
50 print ('%s\t%d' % e)
51 fileout.write('%s, %d\n' % e)
52
53
54 # —————————————————————
55 # cipin(self, doc)
56 # doc: 要读取的文件名
57
58 # return:
59 # 词频表(dataframe格式)
60 # —————————————————————
61 def cipin(self, doc):
62 wdict = {}
63 f = open(doc,"r")
64 for line in f.readlines():
65 words = jieba.cut(line)
66 for w in words:
67 if(w not in wdict):
68 wdict[w] = 1
69 else:
70 wdict[w] += 1
71 # 导入停用词表
72 stop = pd.read_csv('stoplist.txt', encoding = 'utf-8', sep = 'zhao', header = none,engine = 'python') #sep:分割符号(需要用一个确定不会出现在停用词表中的单词)
73 stop.columns = ['word']
74 stop = [' '] + list(stop.word) #python读取时不会读取到空格。但空格依旧需要去除。所以加上空格; 读取后的stop是series的结构,需要转成列表
75 for i in range(len(stop)):
76 if(stop[i] in wdict):
77 wdict.pop(stop[i])
78
79 ind = list(wdict.keys())
80 val = list(wdict.values())
81 ind = pd.series(ind)
82 val = pd.series(val)
83 data = pd.dataframe()
84 data['词'] = ind
85 data['词频'] = val
86 return data
87
88 # —————————————————————
89 # ciyun(self, doc)
90 # doc: 要读取的文件名
91
92 # output:
93 # 词云图
94 # —————————————————————
95 def ciyun(self,doc):
96 g = open(doc,"r").read()
97 back_pic = imread("aixin.jpg") # 设置背景图片
98 wc = wordcloud( font_path='/system/library/fonts/stheiti medium.ttc',#设置字体
99 background_color="white", #背景颜色
100 max_words=2000,# 词云显示的最大词数
101 mask=back_pic,#设置背景图片
102 max_font_size=200, #字体最大值
103 random_state=42,
104 ).generate(g)
105 plt.figure(figsize=(64,32))
106 plt.imshow(wc)
107 plt.axis('off')
108 plt.savefig("ciyun.jpg")
109 plt.show()
110
111
112 def main(self,readdoc):
113 # self.zipin(readdoc,writedoc)
114 df = self.cipin(readdoc)
115 #self.ciyun(readdoc)
116 return df
117
118
119 if __name__ == '__main__':
120 hlm = hlm()
121 hlm.zipin("红楼梦.txt","红楼梦字频.txt")
122 df_hlm1 = hlm.main("红楼梦.txt")
123 ---------------------
124 作者:iovebecky