jieba库的使用

Posted lynn123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jieba库的使用相关的知识,希望对你有一定的参考价值。

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库的使用的主要内容,如果未能解决你的问题,请参考以下文章

jieba库的使用

jieba库的使用

jieba库的使用

jieba库的使用

jieba库的使用

jieba库的使用及实例