jieba 库的安装和使用

本文详细介绍jieba分词库的安装、原理及使用方法,包括三种分词模式:精确模式、全模式和搜索引擎模式。并提供了英文文本《Hamlet》和中文文本《三国演义》的词频分析示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 jieba 库的安装

pip install jieba

2 jieba 库的介绍

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

  • 中文文本需要通过分词获得单个的词语
  • jieba是优秀的中文分词第三方库,需要额外安装
  • jieba库提供三种分词模式,最简单只需掌握一个函数

jieba分词的原理
jieba分词依靠中文词库

  • 利用一个中文词库,确定中文字符之间的关联概率
  • 中文字符间概率大的组成词组,形成分词结果
  • 除了分词,用户还可以添加自定义的词组

3 jieba 库的使用

jieba库的三种模式

  • 精确模式:把文本精确的切分开,不存在冗余单词
  • 全模式:把文本中所有可能的词语都扫描出来,有冗余
  • 搜索引擎模式:在精确模式基础上,对长词再次切分
  • 英文文本:Hamet 分析词频https://python123.io/resources/pye/hamlet.txt
  • 中文文本:《三国演义》 分析人物https://python123.io/resources/pye/threekingdoms.t
英文示例
# 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 = lambda x:x[1],reverse = True)
for i in range(10):
	word,count = items[i]
	print("{0:<10}{1:>5}".format(word,count))

the        1138
and         938
to          751
of          668
a           542
i           528
my          514
you         473
hamlet      433
in          433
中文示例
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
	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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值