运用jieba库分词
一、jieba库基本介绍
jieba库概述
jieba是优秀的中文分词第三方库
-中文文本需要通过分词获得单个的词语
jieba是优秀的中文分词第三方库,需要额外安装
jieba库提供三种分词模式,最简单只需掌握一个函数
2、jieba分词的原理
Jieba分词依靠中文词库
-利用一个中文词库,确定汉字之间的关联概率
汉字间概率大的组成词组,形成分词结果
除了分词,用户还可以添加自定义的词组
3、jieba库使用说明
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
125 来源:CSDN
126 原文:
127 版权声明:本文为博主原创文章,转载请附上博文链接!
代码显示如下:
到这里就结束啦啦啦啦啦~~~~~~~