python中文分词库jieba使用方法详解
安装python中文分词库jieba
法1:Anaconda Prompt下输入conda install jieba
法2:Terminal下输入pip3 install jieba
1、分词
1.1、CUT函数简介
cut(sentence, cut_all=False, HMM=True)
返回生成器,遍历生成器即可获得分词的结果
lcut(sentence)
返回分词列表
import jieba sentence = '我爱自然语言处理' # 创建【Tokenizer.cut 生成器】对象 generator = jieba.cut(sentence) # 遍历生成器,打印分词结果 words = '/'.join(generator) print(words)
打印结果
我/爱/自然语言/处理
import jieba print(jieba.lcut('我爱南海中学'))
打印结果
[‘我', ‘爱', ‘南海中学']
1.2、分词模式
精确模式:精确地切开
全模式:所有可能的词语都切出,速度快
搜索引擎模式:在精确模式的基础上,对长词再次切分
import jieba sentence = '订单数据分析' print('精准模式:', jieba.lcut(sentence)) print('全模式:', jieba.lcut(sentence, cut_all=True)) print('搜索引擎模式:', jieba.lcut_for_search(sentence))
打印结果
精准模式: [‘订单', ‘数据分析']
全模式: [‘订单', ‘订单数', ‘单数', ‘数据', ‘数据分析', ‘分析']
搜索引擎模式: [‘订单', ‘数据', ‘分析', ‘数据分析']
1.3、词性标注
jieba.posseg import jieba.posseg as jp sentence = '我爱Python数据分析' posseg = jp.cut(sentence) for i in posseg: print(i.__dict__) # print(i.word, i.flag)
打印结果
{‘word': ‘我', ‘flag': ‘r'} {‘word': ‘爱', ‘flag': ‘v'} {‘word': ‘Python', ‘flag': ‘eng'} {‘word': ‘数据分析', ‘flag': ‘l'}
词性标注表
1.4、词语出现的位置
jieba.tokenize(sentence) import jieba sentence = '订单数据分析' generator = jieba.tokenize(sentence) for position in generator: print(position)
打印结果
(‘订单', 0, 2) (‘数据分析', 2, 6)
2、词典
2.1、默认词典
import jieba, os, pandas as pd # 词典所在位置 print(jieba.__file__) jieba_dict = os.path.dirname(jieba.__file__) + r'\dict.txt' # 读取字典 df = pd.read_table(jieba_dict, sep=' ', header=None)[[0, 2]] print(df.head()) # 转字典 dt = dict(df.values) print(dt.get('暨南大学'))
2.2、添词和删词
往词典添词
add_word(word, freq=None, tag=None)
往词典删词,等价于add_word(word, freq=0)
del_word(word)
import jieba sentence = '天长地久有时尽,此恨绵绵无绝期' # 添词 jieba.add_word('时尽', 999, 'nz') print('添加【时尽】:', jieba.lcut(sentence)) # 删词 jieba.del_word('时尽') print('删除【时尽】:', jieba.lcut(sentence))
打印结果
添加【时尽】: [‘天长地久', ‘有', ‘时尽', ‘,', ‘此恨绵绵', ‘无', ‘绝期']
删除【时尽】: [‘天长地久', ‘有时', ‘尽', ‘,', ‘此恨绵绵', ‘无', ‘绝期']
2.3、自定义词典加载
新建词典,按照格式【单词 词频 词性】添词,以UTF-8编码保存
使用函数load_userdict加载词典
import os, jieba # 创建自定义字典 my_dict = 'my_dict.txt' with open(my_dict, 'w', encoding='utf-8') as f: f.write('慕容紫英 9 nr\n云天河 9 nr\n天河剑 9 nz') # 加载字典进行测试 sentence = '慕容紫英为云天河打造了天河剑' print('加载前:', jieba.lcut(sentence)) jieba.load_userdict(my_dict) print('加载后:', jieba.lcut(sentence)) os.remove(my_dict)
打印结果
加载前: [‘慕容', ‘紫英为', ‘云', ‘天河', ‘打造', ‘了', ‘天河', ‘剑']
加载后: [‘慕容紫英', ‘为', ‘云天河', ‘打造', ‘了', ‘天河剑']
2.4、使单词中的字符连接或拆分
suggest_freq(segment, tune=False)
import jieba sentence = '上穷碧落下黄泉,两处茫茫皆不见' print('修正前:', ' | '.join(jieba.cut(sentence))) jieba.suggest_freq(('落', '下'), True) print('修正后:', ' | '.join(jieba.cut(sentence)))
打印结果
修正前: 上穷 | 碧 | 落下 | 黄泉 | , | 两处 | 茫茫 | 皆 | 不见
修正后: 上穷 | 碧落 | 下 | 黄泉 | , | 两处 | 茫茫 | 皆 | 不见
3、jieba分词原理
基于词典,对句子进行词图扫描,生成所有成词情况所构成的有向无环图(Directed Acyclic Graph)
根据DAG,反向计算最大概率路径(动态规划算法;取对数防止下溢,乘法运算转为加法)
根据路径获取最大概率的分词序列
import jieba sentence = '中心小学放假' DAG = jieba.get_DAG(sentence) print(DAG) route = {} jieba.calc(sentence, DAG, route) print(route)
DAG
{0: [0, 1, 3], 1: [1], 2: [2, 3], 3: [3], 4: [4, 5], 5: [5]}
最大概率路径
{6: (0, 0), 5: (-9.4, 5), 4: (-12.6, 5), 3: (-20.8, 3), 2: (-22.5, 3), 1: (-30.8, 1), 0: (-29.5, 3)}
4、识别【带空格的词】
示例:使Blade Master这类中间有空格的词被识别
import jieba, re sentence = 'Blade Master疾风刺杀Archmage' jieba.add_word('Blade Master') # 添词 print('修改前:', jieba.lcut(sentence)) jieba.re_han_default = re.compile('(.+)', re.U) # 修改格式 print('修改后:', jieba.lcut(sentence))
打印结果
修改前: [‘Blade', ' ', ‘Master', ‘疾风', ‘刺杀', ‘Archmage']
修改后: [‘Blade Master', ‘疾风', ‘刺杀', ‘Archmage']
5、其它
5.1、并行分词
运行环境:linux系统
开启并行分词模式,参数n为并发数:jieba.enable_parallel(n)
关闭并行分词模式:jieba.disable_parallel()
5.2、关键词提取
基于TF-IDF:jieba.analyse
基于TextRank:jieba.textrank
import jieba.analyse as ja, jieba text = '柳梦璃施法破解了狐仙的法术' jieba.add_word('柳梦璃', tag='nr') keywords1 = ja.extract_tags(text, allowPOS=('n', 'nr', 'ns', 'nt', 'nz')) print('基于TF-IDF:', keywords1) keywords2 = ja.textrank(text, allowPOS=('n', 'nr', 'ns', 'nt', 'nz')) print('基于TextRank:', keywords2)
打印结果
基于TF-IDF: [‘柳梦璃', ‘狐仙', ‘法术']
基于TextRank: [‘狐仙', ‘柳梦璃', ‘法术']
5.3、修改HMM参数
import jieba text = '柳梦璃解梦C法' print(jieba.lcut(text, HMM=False)) # ['柳', '梦', '璃', '解梦', 'C', '法'] print(jieba.lcut(text)) # ['柳梦璃', '解梦', 'C', '法'] jieba.finalseg.emit_P['B']['C'] = -1e-9 # begin print(jieba.lcut(text)) # ['柳梦璃', '解梦', 'C', '法'] jieba.finalseg.emit_P['M']['梦'] = -100 # middle print(jieba.lcut(text)) # ['柳', '梦璃', '解梦', 'C', '法'] jieba.finalseg.emit_P['S']['梦'] = -.1 # single print(jieba.lcut(text)) # ['柳', '梦', '璃', '解梦', 'C', '法'] jieba.finalseg.emit_P['E']['梦'] = -.01 # end print(jieba.lcut(text)) # ['柳梦', '璃', '解梦', 'C', '法'] jieba.del_word('柳梦') # Force_Split_Words print(jieba.lcut(text)) # ['柳', '梦', '璃', '解梦', 'C', '法']
[‘柳', ‘梦', ‘璃', ‘解梦', ‘C', ‘法']
[‘柳梦璃', ‘解梦', ‘C', ‘法']
[‘柳梦璃', ‘解梦', ‘C', ‘法']
[‘柳', ‘梦璃', ‘解梦', ‘C', ‘法']
[‘柳', ‘梦', ‘璃', ‘解梦', ‘C', ‘法']
[‘柳梦', ‘璃', ‘解梦', ‘C', ‘法']
[‘柳', ‘梦', ‘璃', ‘解梦', ‘C', ‘法']
更多关于python中文分词库jieba使用方法请查看下面的相关链接
下一篇:Python版中国省市经纬度