https://i.cnblogs.com/settings

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))

  

posted @ 2019-11-29 15:21  LLLN  阅读(308)  评论(0)    收藏  举报
Copyright © 2021 llln Powered by .NET 5.0 on Kubernetes