安装库函数
(1) 在命令行下输入指令:
pip install jieba
(2) 安装进程:
调用库函数
(1) 导入库函数:import <库名>
使用库中函数:<库名> . <函数名> (<函数参数>)
(2) 导入库函数:from <库名> import * ( *为通配符 )
使用库中函数:<函数名> (<函数参数>)
jieba 库函数
(1) 库函数功能
模式 | 函数 | 说明 |
精确模式 | cut(s) | 返回一个可迭代数据类型 |
lcut(s) | 返回一个列表类型 (建议使用) | |
全模式 | cut(s,cut_all=True) | 输出s中所以可能的分词 |
lcut(s,cut_all=True) | 返回一个列表类型 (建议使用) | |
搜索引擎模式 | cut_for_search(s) | 适合搜索引擎建立索引的分词结果 |
lcut_for_search(s) | 返回一个列表类型 (建议使用) | |
自定义新词 | add_word(w) | 向分词词典中增加新词w |
(2) 函数使用实例
对一篇文档进行词频统计
(1) jieba 库单枪匹马
A. 代码实现
注:代码使用的文档 >>> Detective_Novel(utf-8).zip [点击下载],也可自行找 utf-8 编码格式的txt文件。
# -*- coding:utf-8 -*-
from jieba import *
def Replace(text,old,new): #替换列表的字符串
for char in old:
text = text.replace(char,new)
return text
def getText(filename): #读取文件内容(utf-8 编码格式)
#特殊符号和部分无意义的词
sign = '''!~·@¥……*“”‘’\n(){}【】;:"'「,」。-、?'''
txt = open('{}.txt'.format(filename),encoding='utf-8').read()
return Replace(txt,sign," ")
def word_count(passage,N): #计算passage文件中的词频数,并将前N个输出
words = lcut(passage) #精确模式分词形式
counts = {} #创建计数器 --- 字典类型
for word in words: #消除同意义的词和遍历计数
if word == '小五' or word == '小五郎' or word == '五郎':
rword = '毛利'
elif word == '柯' or word == '南':
rword = '柯南'
elif word == '小' or word == '兰':
rword = '小兰'
elif word == '目' or word == '暮' or word == '警官':
rword = '暮目'
else:
rword = word
counts[rword] = counts.get(rword,0) + 1
excludes = lcut_for_search("你我事他和她在这也有什么的是就吧啊吗哦呢都了一个")
for word in excludes: #除去意义不大的词语
del(counts[word])
items = list(counts.items()) #转换成列表形式
items.sort(key = lambda x : x[1], reverse = True ) #按次数排序
for i in range(N): #依次输出
word,count = items[i]
print("{:<7}{:>6}".format(word,count))
if __name__ == '__main__':
passage = getText('Detective_Novel') #输入文件名称读入文件内容
word_count(passage,20) #调用函数得到词频数
B. 执行结果
(2) jieba 库 和 wordcloud 库 强强联合 --- 词云图
A. 代码实现
# -*- coding:utf-8 -*-
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from jieba import *
def Replace(text,old,new): #替换列表的字符串
for char in old:
text = text.replace(char,new)
return text
def getText(filename): #读取文件内容(utf-8 编码格式)
#特殊符号和部分无意义的词
sign = '''!~·@¥……*“”‘’\n(){}【】;:"'「,」。-、?'''
txt = open('{}.txt'.format(filename),encoding='utf-8').read()
return Replace(txt,sign," ")
def creat_word_cloud(filename): #将filename 文件的词语按出现次数输出为词云图
text = getText(filename) #读取文件
wordlist = lcut(text) #jieba库精确模式分词
wl = ' '.join(wordlist) #生成新的字符串
#设置词云图
font = r'C:\Windows\Fonts\simfang.ttf' #设置字体路径
wc = WordCloud(
background_color = 'black', #背景颜色
max_words = 2000, #设置最大显示的词云数
font_path = font, #设置字体形式(在本机系统中)
height = 1200, #图片高度
width = 1600, #图片宽度
max_font_size = 100, #字体最大值
random_state = 100, #配色方案的种类
)
myword = wc.generate(wl) #生成词云
#展示词云图
plt.imshow(myword)
plt.axis('off')
plt.show()
#以原本的filename命名保存词云图
wc.to_file('{}.png'.format(filename))
if __name__ == '__main__':
creat_word_cloud('Detective_Novel') #输入文件名生成词云图
B. 执行结果