码迷,mamicode.com
首页 > 其他好文 > 详细

jieba库的使用

时间:2019-11-29 15:55:19      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:item   add   中文分词   sort   lse   oms   存在   英文   alt   

jieba是优秀的中文分词第三方库

jieba有3种模式

1.精确模式,返回一个列表类型的分词结果

>>>jieba.lcut("中国是一个伟大的国家")
[‘中国‘, ‘是‘, ‘一个‘, ‘伟大‘, ‘的‘, ‘国家‘]

2.全模式,返回一个列表类型的分词结果,存在冗余

>>>jieba.lcut("中国是一个伟大的国家",cut_all=True)
[‘中国‘, ‘国是‘, ‘一个‘, ‘伟大‘, ‘的‘, ‘国家‘]

3.搜索引擎模式,返回一个列表类型的分词结果,存在冗余

>>>jieba.lcut_for_search(“中华人民共和国是伟大的")
[‘中华‘, ‘华人‘, ‘人民‘, ‘共和‘, ‘共和国‘, ‘中华人民共和国‘, ‘是‘, ‘伟大‘, ‘的‘]

jieba向分词词典增加新词

jieba.add_word(w)

>>>jieba.add_word("蟒蛇语言")

 

实例一:Hamlet英文词频统

#CalHamletV1.py
def getText():
    txt = open("hamlet.txt", "r").read()
    txt = txt.lower()
    for ch in‘!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~‘:
        txt = txt.replace(ch, " ")
    return txt
hamletTxt= getText()
words = hamletTxt.split()
counts = {}
    for word in words:
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambdax:x[1], reverse=True)
for i in range(10):
    word, count = items[i]
    print("{0:<10}{1:>5}".format(word, count))

实例二:中文文本分词

#CalThreeKingdomsV1.py
import jieba
txt = open("threekingdoms.txt", "r", encoding="utf-8").read()
words = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:
        continue
  elif word =="1" or word=="2":               #加上elif后滤除1、2人称谓显示,只显示3称谓
      rword=="3"
    else:
        counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(15):
    word, count = items[i]
    print("{0:<10}{1:>5}".format(word, count))

  

jieba库的使用

标签:item   add   中文分词   sort   lse   oms   存在   英文   alt   

原文地址:https://www.cnblogs.com/Lynn123/p/11957978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!