jieba库的使用及实例
安装:
cmd模式下输入
pip install jieba
anaconda对应环境
conda install jieba
分词原理:
Jieba分词依靠中文词库
-利用一个中文词库,确定汉字之间的关联概率
-汉字间概率大的组成词组,形成分词结果
-除了分词,用户还可以添加自定义的词组
jieba库的三种模式:
-精确模式:把文本精确的切分开,不存在冗余单词
#jieba.lcut(s) jieba.lcut("中国是一个伟大的国家") #output:[‘中国‘, ‘是‘, ‘一个‘, ‘伟大‘, ‘的‘, ‘国家‘]
-全模式:把文本中所有的可能的词语都扫描出来,有冗余
#jieba.lcut(s,cut_all=True) jieba.lcut("中国是一个伟大的国家",cut_all=True) #output:[‘中国‘, ‘国是‘, ‘一个‘, ‘伟大‘, ‘的‘, ‘国家‘]
-全搜索引擎模式:在精确模式的基础上,对长词再次切分
#jieba.lcut_for_search(s) jieba.lcut_for_search("中华人民共和国是伟大的") #output:[‘中华‘, ‘华人‘, ‘人民‘, ‘共和‘, ‘共和国‘, ‘中华人民共和国‘, ‘是‘, ‘伟大‘, ‘的‘]
向分词词典中增加新词w:
#jieba.add_word(w) jieba.add_word("蟒蛇语言")
#CalThreeKingdomsV2.py #统计三国人物出场频率 url=‘https://python123.io/resources/pye/threekingdoms.txt‘ import jieba, requests def getText(): #下载到本地,或者直接爬下来 #txt = open(‘threekingdoms.txt‘,‘r‘,encoding= ‘utf-8‘).read() try: re = requests.get(url=‘https://python123.io/resources/pye/threekingdoms.txt‘,timeout=30) re.raise_for_status() #如果状态不是200引发HTTPError异常 re.encoding = re.apparent_encoding return re.text except: return ‘‘ #剔除非名字 excludes = {"将军",‘却说‘,‘荆州‘,‘二人‘,‘不可‘,‘军马‘,‘引兵‘,‘次日‘,‘大喜‘, ‘不能‘,‘如此‘,‘商议‘,‘如何‘,‘军士‘,‘左右‘,‘\r\n‘} words = jieba.lcut(getText()) counts = {} for word in words: if len(word) == 1 : continue elif ‘诸葛亮‘ == word or ‘孔明曰‘==word: rword = ‘孔明‘ elif ‘关公‘ == word or ‘云长‘ == word: rword = ‘关羽‘ elif ‘玄德‘ ==word or ‘玄德曰‘ ==word: rword = ‘刘备‘ elif ‘孟德‘==word: rword = ‘曹操‘ else: rword = word counts[rword] = counts.get(rword,0)+1 for word in excludes: if word in counts: del counts[word] items = list(counts.items()) items.sort(key= lambda x:x[1],reverse=True) for i in range(10): word, count = items[i] print(‘{0:<10}{1:>5}‘.format(word,count))
(learn) D:\pycodes>python CalThreeKingdomsV2.py
Building prefix dict from the default dictionary ...
Loading model from cache C:\Users\hao11\AppData\Local\Temp\jieba.cache
Loading model cost 0.625 seconds.
Prefix dict has been built successfully.
孔明 1383
刘备 1252
曹操 960
关羽 784
丞相 491
张飞 358
主公 331
吕布 300
赵云 278
孙权 264
有许多地方可以优化,丞相和主公这类词,可以特殊处理。
jieba.lcut("淡黄的长裙,蓬松的头发")[‘淡黄‘, ‘的‘, ‘长裙‘, ‘,‘, ‘蓬松‘, ‘的‘, ‘头发‘]
相关推荐
kikaylee 2020-07-05
zooozx 2020-06-27
xiaocao0 2020-06-25
pySVNA 2020-06-14
fkyyly 2020-05-31
ustbclearwang 2020-05-09
cqulun 2020-04-19
chongtianfeiyu 2020-04-10
xiaocao0 2020-04-09
fkyyly 2020-04-07
chouliqingke 2020-04-07
cqulun 2020-02-13
cqulun 2020-02-10
laityc 2020-02-10
wordmhg 2020-02-09
小发猫 2020-02-02
fkyyly 2020-01-28