jieba庫的使用


jieba庫是一款優秀的 Python 第三方中文分詞庫,jieba 支持三種分詞模式:精確模式、全模式和搜索引擎模式,下面是三種模式的特點。

精確模式:試圖將語句最精確的切分,不存在冗余數據,適合做文本分析

全模式:將語句中所有可能是詞的詞語都切分出來,速度很快,但是存在冗余數據

搜索引擎模式:在精確模式的基礎上,對長詞再次進行切分

一、jieba庫的安裝
因為 jieba 是一個第三方庫,所有需要我們在本地進行安裝。

Windows 下使用命令安裝:在聯網狀態下,在命令行下輸入 pip install jieba進行安裝,安裝完成后會提示安裝成功

在 pyCharm 中安裝:打開 settings,搜索 Project Interpreter,在右邊的窗口選擇 + 號,點擊后在搜索框搜索 jieba,點擊安裝即可

二、jieba三種模式的使用

# -*- coding: utf-8 -*-
import jieba

seg_str = "好好學習,天天向上。"

print("/".join(jieba.lcut(seg_str))) # 精簡模式,返回一個列表類型的結果
print("/".join(jieba.lcut(seg_str, cut_all=True))) # 全模式,使用 'cut_all=True' 指定 
print("/".join(jieba.lcut_for_search(seg_str))) # 搜索引擎模式

分詞效果:

三、jieba 分詞簡單應用
需求:使用 jieba 分詞對一個文本進行分詞,統計次數出現最多的詞語,這里以三國演義為例

# -*- coding: utf-8 -*-
import jieba

txt = open("三國演義.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 # 遍歷所有詞語,每出現一次其對應的值加 1

items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True) # 根據詞語出現的次數進行從大到小排序

for i in range(3):
word, count = items[i]
print("{0:<5}{1:>5}".format(word, count))
統計結果:

可隨便找一個文本文檔,也可以到 https://github.com/coderjas/python-quick 下載上面例子中的文檔。

四、擴展:英文單詞統計
上面的例子統計實現了中文文檔中出現最多的詞語,接着我們就來統計一下一個英文文檔中出現次數最多的單詞。原理同上

# -*- coding: utf-8 -*-

def get_text():
txt = open("1.txt", "r", encoding='UTF-8').read()
txt = txt.lower()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(ch, " ") # 將文本中特殊字符替換為空格
return txt

file_txt = get_text()
words = file_txt.split() # 對字符串進行分割,獲得單詞列表
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(5):
word, count = items[i]
print("{0:<5}->{1:>5}".format(word, count))

統計結果:

 

 

 

 

 

轉自:https://blog.csdn.net/codejas/article/details/80356544


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM