Python启航:30天编程速成之旅(第27天)- jieba

Python启航:30天编程速成之旅(第27天)- jieba

编程文章jaq1232025-02-26 10:55:0822A+A-

喜欢的条友记得关注、点赞、转发、收藏,你们的支持就是我最大的动力源泉。

前期基础教程:

「Python3.11.0」手把手教你安装最新版Python运行环境

讲讲Python环境使用Pip命令快速下载各类库的方法

Python启航:30天编程速成之旅(第2天)-IDE安装

【Python教程】JupyterLab 开发环境安装


Python 中jieba模块的完整详细教程

jieba 是一个非常流行的中文分词库,支持多种分词模式,并且易于使用。它可以帮助你将中文文本分割成词语,这对于自然语言处理(NLP)任务非常重要,比如文本分类、情感分析、关键词提取等。本教程将详细介绍 jieba 的安装、基本用法、高级功能以及一些生动的例子,帮助你更好地理解和使用这个强大的工具。

1. 安装jieba

jieba 是一个第三方库,你需要通过 pip 来安装它。打开命令行并执行以下命令:

pip install jieba

2. 基本用法

导入jieba

安装完成后,你可以通过以下方式导入 jieba:

import jieba

精确模式分词

jieba 提供了多种分词模式,默认是精确模式,适用于对准确性要求较高的场景。

text = "我的祖籍在河南济源,我的户口在河南开封,目前我在河南郑州工作。"
words = jieba.lcut(text)
print(words)

lcut 方法返回一个列表,包含分词后的词语。如果你想直接打印分词结果,可以使用 cut 方法并结合 join 函数:

text = "我的祖籍在河南济源,我的户口在河南开封,目前我在河南郑州工作。"
words = jieba.cut(text)
print(" ".join(words))

全模式分词

全模式会将所有可能的词语都切分出来,适用于搜索引擎等需要召回率较高的场景。

text = "我的祖籍在河南济源,我的户口在河南开封,目前我在河南郑州工作。"
words = jieba.lcut(text, cut_all=True)
print(words)

搜索引擎模式分词

搜索引擎模式在精确模式的基础上,对长词再次切分,以提高召回率。

text = "我的祖籍在河南济源,我的户口在河南开封,目前我在河南郑州工作。"
words = jieba.lcut_for_search(text)
print(words)

3. 添加自定义词典

jieba 支持自定义词典,这有助于提高特定领域或特定词汇的分词准确性。你可以通过 load_userdict 方法加载自定义词典文件。

创建自定义词典文件

创建一个名为 user_dict.txt 的文件,每行包含一个词条及其权重(可选)。例如:

河南济源
河南开封
河南郑州

加载自定义词典

import jieba

# 加载自定义词典
jieba.load_userdict("user_dict.txt")

text = "我的祖籍在河南济源,我的户口在河南开封,目前我在河南郑州工作。"
words = jieba.lcut(text)
print(words)

4. 关键词提取

jieba 提供了 extract_tags 方法来提取文本中的关键词。你可以指定要提取的关键词数量和权重算法。

import jieba.analyse

text = "我的祖籍在河南济源,我的户口在河南开封,目前我在河南郑州工作。"

# 提取前 5 个关键词
keywords = jieba.analyse.extract_tags(text, topK=5)
print(keywords)

# 使用 TF-IDF 算法提取关键词
tfidf_keywords = jieba.analyse.tfidf(text, topK=5)
print(tfidf_keywords)

# 使用 TextRank 算法提取关键词
textrank_keywords = jieba.analyse.textrank(text, topK=5)
print(textrank_keywords)

5. 词频统计

jieba 可以与 collections.Counter 结合使用,来进行词频统计。

import jieba
from collections import Counter

text = "我喜欢编程,编程让我快乐。编程是解决问题的好方法。"
words = jieba.lcut(text)

# 统计词频
word_counts = Counter(words)
print(word_counts)
# 打印最常见的 3 个词
most_common_words = word_counts.most_common(3)
print(most_common_words)

6. 词性标注

jieba 还提供了词性标注的功能,可以结合 jieba.posseg 模块使用。

import jieba.posseg as pseg

text = "我的祖籍在河南济源,我的户口在河南开封,目前我在河南郑州工作。"
words = pseg.cut(text)

for word, flag in words:
    print(f"{word}({flag})")

7. 生动的例子

示例 1:分析微博评论

假设你有一个文本文件 comments.txt,你想分析其中的关键词和情感倾向。

我的祖籍在河南济源,我的户口在河南开封,目前我在河南郑州工作,我热爱我的家乡河南,更加热爱我的故乡。

安装snownlp库:

pip install snownlp
import jieba.analyse
from snownlp import SnowNLP

def analyze_weibo_comments(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        comments = f.read()

    # 提取关键词
    keywords = jieba.analyse.extract_tags(comments, topK=10)
    print("关键词:", keywords)

    # 分析情感倾向
    s = SnowNLP(comments)
    sentiment_score = s.sentiments  # 返回一个 0 到 1 之间的值,越接近 1 表示越积极
    print("情感得分:", sentiment_score)

# 使用示例
analyze_weibo_comments('comments.txt')

示例 2:生成词云

结合 wordcloud 库,你可以生成一个基于分词结果的词云图。

安装wordcloud库:

pip install wordcloud
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt

def generate_wordcloud(text, output_image):
    # 分词
    words = jieba.lcut(text)
    word_string = " ".join(words)

    # 生成词云
    wordcloud = WordCloud(font_path='simhei.ttf', width=800, height=400, background_color='white').generate(word_string)

    # 显示词云
    plt.figure(figsize=(10, 5))
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis('off')
    plt.savefig(output_image)
    plt.show()

# 使用示例
text = "我的祖籍在河南济源,我的户口在河南开封,目前我在河南郑州工作,我热爱我的家乡河南,更加热爱我的故乡。"
generate_wordcloud(text, 'wordcloud.png')

示例 3:构建倒排索引

假设你有一个文档集合,想要构建一个简单的倒排索引来加速搜索。

import jieba
from collections import defaultdict

def build_inverted_index(documents):
    inverted_index = defaultdict(list)
    
    for doc_id, text in enumerate(documents):
        words = set(jieba.lcut(text))
        for word in words:
            inverted_index[word].append(doc_id)
    
    return inverted_index

def search(query, inverted_index):
    query_words = set(jieba.lcut(query))
    result = set()
    
    for word in query_words:
        if word in inverted_index:
            result.update(inverted_index[word])
    
    return result

# 使用示例
documents = [
    "我喜欢编程,编程让我快乐。",
    "编程是解决问题的好方法。",
    "我喜欢学习新知识。",
]

inverted_index = build_inverted_index(documents)
query = "编程 快乐"
result = search(query, inverted_index)
print("搜索结果:", [documents[i] for i in result])

8. 高级功能

并行分词

对于大量文本的分词任务,jieba 提供了并行分词的功能,可以显著提高处理速度。

import jieba
from multiprocessing import Pool, set_start_method

def init_jieba():
    # 在每个子进程中重新初始化 jieba
    import jieba
    jieba.initialize()

def parallel_cut(text):
    return jieba.lcut(text)

if __name__ == '__main__':
    # 在 Windows 上,必须显式设置启动方法为 'spawn'
    set_start_method('spawn')

    texts = ["我喜欢编程", "编程让我快乐", "编程是解决问题的好方法"]

    # 创建进程池,并在每个子进程中调用 init_jieba
    with Pool(initializer=init_jieba) as pool:
        results = pool.map(parallel_cut, texts)

    print(results)

自定义分词规则

你可以通过 add_word 和 del_word 方法来添加或删除自定义的分词规则。

import jieba

# 添加自定义词汇前
text = "这是一个包含自定义词汇的句子"
words = jieba.lcut(text)
print(words)  # 输出: ['这是', '一个', '包含', '自定义词汇', '的', '句子']

# 添加自定义词汇后
jieba.add_word("自定义词汇")
jieba.add_word("这是一个", freq=1000, tag=None)

words = jieba.lcut(text)
print(words)  # 输出: ['这是', '一个', '包含', '自定义词汇', '的', '句子']

9. 总结

jieba 是一个功能强大且易于使用的中文分词库,广泛应用于各种自然语言处理任务中。通过本教程,你已经了解了 jieba 的基本用法、高级功能以及一些生动的例子。希望这些内容能够帮助你更好地掌握 jieba,并在你的项目中应用它。

如果你有更多问题或需要进一步的帮助,请随时提问!

喜欢的条友记得关注、点赞、转发、收藏,你们的支持就是我最大的动力源泉。

点击这里复制本文地址 以上内容由jaq123整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

苍茫编程网 © All Rights Reserved.  蜀ICP备2024111239号-21