Python 中文分词:jieba库的使用

简介: Python基础入门jieba库的使用。如何安装,常用函数方法。老人与海、水浒传词频统计案例。
✅作者简介:人工智能专业本科在读,喜欢计算机与编程,写博客记录自己的学习历程。
🍎个人主页: 小嗷犬的博客
🍊个人信条:为天地立心,为生民立命,为往圣继绝学,为万世开太平。
🥭本文内容:Python 中文分词:jieba库的使用

1.jieba库的安装

jieba是Python中一个重要的第三方中文分词函数库,需要通过pip指令安装:
pip install jieba   
# 或者 
pip3 install jieba

2.常用函数方法

jieba库的常用函数方法如下:
函数 描述
jieba.cut(s) 精确模式,返回一个可迭代的数据类型
jieba.cut(s, cut_all=True) 全模式,输出文本s中所有可能单词
jieba.cut_for_search(s) 搜索引擎模式,适合搜索引擎建立索引的分词结果
jieba.lcut(s) 精确模式,返回一个列表类型,建议使用
jieba.lcut(s, cut_all=True) 全模式,返回一个列表类型,建议使用
jieba.add_word(w) 向分词词典中增加新词w
代码实例:
import jieba
print(jieba.lcut('Python是一种十分便捷的编程语言'))
print(jieba.lcut('Python是一种十分便捷的编程语言', cut_all=True))
print(jieba.lcut_for_search('Python是一种十分便捷的编程语言'))

3.jieba库的应用:文本词频统计

3.1 《The Old Man And the Sea》英文词频统计

import jieba
def getText():
    txt = open("Documents/《The Old Man And the Sea》.txt", "r", encoding='utf-8').read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")   #将文本中特殊字符替换为空格
    return txt

words  = getText().split()
counts = {}
for word in words:
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items[:10]
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        2751
# and        1458
# he         1221
# of          788
# to          555
# a           538
# it          528
# his         513
# in          503
# i           472
观察输出结果可以看到,高频单词大多数是冠词、代词、连接词等语法型词汇,并不能代表文章的含义。进一步,可以采用集合类型构建一个排除词汇库 excludes,在输出结果中排除这个词汇库中内容。
excludes = {"the","and","of","you","a","i","my","in","he","to","it","his","was",
            "that","is","but","him","as","on","not","with","had","said","now","for",
           "thought","they","have","then","were","from","could","there","out","be",
           "when","at","them","all","will","would","no","do","are","or","down","so",
            "up","what","if","back","one","can","must","this","too","more","again",
           "see","great","two"}

def getText():
    txt = open("Documents/《The Old Man And the Sea》.txt", "r", encoding='utf-8').read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~“”':
        txt = txt.replace(ch, " ")   #将文本中特殊字符替换为空格
    return txt

words  = getText().split()
counts = {}
for word in words:
    counts[word] = counts.get(word,0) + 1
for word in excludes:
    del(counts[word])
items = list(counts.items())
items[:10]
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))
# 输出:
# old         300
# man         298
# fish        281
# line        139
# water       107
# boy         105
# hand         91
# sea          67
# head         65
# come         60

3.2 《水浒传》人物出场统计

import jieba

txt = open("Documents/《水浒传》.txt", "r", encoding='utf-8').read()
words  = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:  #排除单个字符的分词结果
        continue
    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))
# 输出:
# 宋江         2538
# 两个         1733
# 一个         1399
# 李逵         1117
# 武松         1053
# 只见          917
# 如何          911
# 那里          858
# 哥哥          750
# 说道          729
# 林冲          720
# 军马          719
# 头领          707
# 吴用          654
# 众人          652
观察输出,我们发现结果中有非人名词汇,与英文词频统计类似,我们需要排除一些人名无关词汇。
import jieba
excludes = {'两个','一个','只见','如何','那里','哥哥','说道','军马',
           '头领','众人','这里','兄弟','出来','小人','梁山泊','这个',
           '今日','妇人','先锋','好汉','便是','人马','问道','起来',
           '甚么','因此','却是','我们','正是','三个','如此','且说',
           '不知','不是','只是','次日','不曾','呼延','不得','一面',
           '看时','不敢','如今','来到','当下','原来','将军','山寨',
           '喝道','兄长','只得','军士','里面','大喜','天子','一齐',
           '知府','性命','商议','小弟','那个','公人','将来','前面',
            '东京','喽罗','那厮','城中','弟兄','下山','不见','怎地',
            '上山','随即','不要'}



txt = open("Documents/《水浒传》.txt", "r", encoding='utf-8').read()
words  = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:
        continue
    elif word == "宋江道":
        rword = "宋江"
    else:
        rword = word
    counts[rword] = counts.get(rword,0) + 1
for word in excludes:
    del(counts[word])
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))
# 输出:
# 宋江         3010
# 李逵         1117
# 武松         1053
# 林冲          720
# 吴用          654
# 卢俊义         546
# 鲁智深         356
# 戴宗          312
# 柴进          301
# 公孙胜         272
# 花荣          270
# 秦明          258
# 燕青          252
# 朱仝          245
# 晁盖          238
目录
相关文章
|
2月前
|
存储 Web App开发 前端开发
Python + Requests库爬取动态Ajax分页数据
Python + Requests库爬取动态Ajax分页数据
|
5月前
|
JavaScript 前端开发 Java
通义灵码 Rules 库合集来了,覆盖Java、TypeScript、Python、Go、JavaScript 等
通义灵码新上的外挂 Project Rules 获得了开发者的一致好评:最小成本适配我的开发风格、相当把团队经验沉淀下来,是个很好功能……
1116 103
|
2月前
|
JSON 网络安全 数据格式
Python网络请求库requests使用详述
总结来说,`requests`库非常适用于需要快速、简易、可靠进行HTTP请求的应用场景,它的简洁性让开发者避免繁琐的网络代码而专注于交互逻辑本身。通过上述方式,你可以利用 `requests`处理大部分常见的HTTP请求需求。
273 51
|
1月前
|
数据采集 存储 Web App开发
Python爬虫库性能与选型实战指南:从需求到落地的全链路解析
本文深入解析Python爬虫库的性能与选型策略,涵盖需求分析、技术评估与实战案例,助你构建高效稳定的数据采集系统。
216 0
|
2月前
|
存储 监控 安全
Python剪贴板监控实战:clipboard-monitor库的深度解析与扩展应用
本文介绍如何利用Python的clipboard-monitor库实现剪贴板监控系统,涵盖文本与图片的实时监听、防重复存储、GUI界面开发及数据加密等核心技术,适用于安全审计与自动化办公场景。
81 0
|
3月前
|
JSON 数据格式 Python
解决Python requests库POST请求参数顺序问题的方法。
总之,想要在Python的requests库里保持POST参数顺序,你要像捋顺头发一样捋顺它们,在向服务器炫耀你那有条不紊的数据前。抓紧手中的 `OrderedDict`与 `json`这两把钥匙,就能向服务端展示你的请求参数就像经过高端配置的快递包裹,里面的商品摆放井井有条,任何时候开箱都是一种享受。
88 10
|
3月前
|
XML JSON 安全
分析参数顺序对Python requests库进行POST请求的影响。
最后,尽管理论上参数顺序对POST请求没影响,但编写代码时仍然建议遵循一定的顺序和规范,比如URL总是放在第一位,随后是data或json,最后是headers,这样可以提高代码的可读性和维护性。在处理复杂的请求时,一致的参数顺序有助于调试和团队协作。
124 9
|
7月前
|
Web App开发 数据采集 数据安全/隐私保护
Selenium库详解:Python实现模拟登录与反爬限制的进阶指南
Selenium库详解:Python实现模拟登录与反爬限制的进阶指南

热门文章

最新文章

推荐镜像

更多