当前位置:   article > 正文

jieba库的安装和应用_jieba库安装

jieba库安装

目录

        一、jieba库

        二、 jieba库的安装

         三、jieba三种模式的使用

        四、jieba 分词简单应用

        五、扩展:英文单词统计


一、jieba库

        jieba库是一款优秀的 Python 第三方中文分词库jieba 支持三种分词模式:精确模式、全模式和搜索引擎模式,下面是三种模式的特点。

精确模式:试图将语句最精确的切分,不存在冗余数据,适合做文本分析

全模式:将语句中所有可能是词的词语都切分出来,速度很快,但是存在冗余数据

搜索引擎模式:在精确模式的基础上,对长词再次进行切分

二、 jieba库的安装

因为 jieba 是一个第三方库,所有需要我们在本地进行安装。

Windows 下使用命令安装:在联网状态下,在命令行下输入 pip install jieba 进行安装,安装完成后会提示安装成功。

 pip install jieba 

 在 pyCharm 中安装:打开 settings,搜索 Project Interpreter,在右边的窗口选择 + 号,点击后在搜索框搜索 jieba,点击安装即可

 三、jieba三种模式的使用

  1. # -*- coding: utf-8 -*-
  2. import jieba
  3. seg_str = "好好学习,天天向上。"
  4. print("/".join(jieba.lcut(seg_str))) # 精简模式,返回一个列表类型的结果
  5. print("/".join(jieba.lcut(seg_str, cut_all=True))) # 全模式,使用 'cut_all=True' 指定
  6. print("/".join(jieba.lcut_for_search(seg_str))) # 搜索引擎模式

分词效果:

这里写图片描述

四、jieba 分词简单应用

需求:使用 jieba 分词对一个文本进行分词,统计次数出现最多的词语,这里以三国演义为例

  1. # -*- coding: utf-8 -*-
  2. import jieba
  3. txt = open("三国演义.txt", "r", encoding='utf-8').read()
  4. words = jieba.lcut(txt) # 使用精确模式对文本进行分词
  5. counts = {} # 通过键值对的形式存储词语及其出现的次数
  6. for word in words:
  7. if len(word) == 1: # 单个词语不计算在内
  8. continue
  9. else:
  10. counts[word] = counts.get(word, 0) + 1 # 遍历所有词语,每出现一次其对应的值加 1
  11. items = list(counts.items())
  12. items.sort(key=lambda x: x[1], reverse=True) # 根据词语出现的次数进行从大到小排序
  13. for i in range(3):
  14. word, count = items[i]
  15. print("{0:<5}{1:>5}".format(word, count))

统计结果:

这里写图片描述

你可以随便找一个文本文档,也可以到 https://github.com/coderjas/python-quick 下载上面例子中的文档。

五、扩展:英文单词统计

上面的例子统计实现了中文文档中出现最多的词语,接着我们就来统计一下一个英文文档中出现次数最多的单词。原理同上

  1. # -*- coding: utf-8 -*-
  2. def get_text():
  3. txt = open("1.txt", "r", encoding='UTF-8').read()
  4. txt = txt.lower()
  5. for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
  6. txt = txt.replace(ch, " ") # 将文本中特殊字符替换为空格
  7. return txt
  8. file_txt = get_text()
  9. words = file_txt.split() # 对字符串进行分割,获得单词列表
  10. counts = {}
  11. for word in words:
  12. if len(word) == 1:
  13. continue
  14. else:
  15. counts[word] = counts.get(word, 0) + 1
  16. items = list(counts.items())
  17. items.sort(key=lambda x: x[1], reverse=True)
  18. for i in range(5):
  19. word, count = items[i]
  20. print("{0:<5}->{1:>5}".format(word, count))

统计结果:

这里写图片描述

 注:本篇文章参考Python入门:jieba库的使用_jieba库的用法_留兰香丶的博客-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/344040
推荐阅读
  

闽ICP备14008679号