以下是用jieba分词和词云分析文本的完整教程,包含代码实现和关键步骤解析:


一、核心工具安装

pip install jieba wordcloud matplotlib numpy pillow


二、文本分词处理

import jieba

# 1. 基础分词
text = "自然语言处理是人工智能的重要方向"
words = jieba.cut(text)
print("/".join(words))  # 输出:自然/语言/处理/是/人工智能/的/重要/方向

# 2. 全模式分词
words_full = jieba.cut(text, cut_all=True)
print("/".join(words_full))  # 输出:自然/语言/处理/是/人工/人工智能/智能/重要/方向

# 3. 加载自定义词典
jieba.load_userdict("user_dict.txt")  # 文件格式:每行一个词


三、停用词过滤

stopwords = set()
with open("stopwords.txt", "r", encoding="utf-8") as f:  # 停用词表
    for line in f:
        stopwords.add(line.strip())

filtered_words = [word for word in words if word not in stopwords and len(word) > 1]


四、词频统计

from collections import Counter

word_counts = Counter(filtered_words)
top10 = word_counts.most_common(10)
print(top10)  # 示例输出:[('人工智能', 12), ('处理', 9), ('语言', 7)...]


五、生成词云

from wordcloud import WordCloud
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

# 1. 基础词云
wc = WordCloud(
    font_path="msyh.ttc",      # 中文字体路径
    background_color="white",  # 背景色
    max_words=200,             # 最大词数
    width=800, height=600      # 尺寸
)
wc.generate_from_frequencies(word_counts)

# 2. 显示词云
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()

# 3. 保存结果
wc.to_file("wordcloud.png")


六、进阶技巧

  1. 形状词云
mask = np.array(Image.open("china_map.png"))  # 加载形状蒙版
wc = WordCloud(mask=mask, contour_width=2, contour_color='steelblue')

  1. 配色方案
from wordcloud import ImageColorGenerator
color_func = ImageColorGenerator(mask)  # 从图片取色
wc.recolor(color_func=color_func)

  1. 词云优化参数
WordCloud(
    collocations=False,  # 禁用词组重复
    prefer_horizontal=0.8,  # 横排词比例
    colormap="viridis",  # 配色方案
    min_font_size=10     # 最小字号
)


七、完整流程示例

# 读取文本
with open("article.txt", "r", encoding="utf-8") as f:
    text = f.read()

# 分词+过滤
words = [word for word in jieba.cut(text) 
         if word not in stopwords and len(word) > 1]

# 生成词云
word_counts = Counter(words)
wc = WordCloud(font_path="simhei.ttf", 
               width=1000, height=700,
               background_color="white",
               max_words=150).generate_from_frequencies(word_counts)

# 显示并保存
plt.figure(figsize=(12,8))
plt.imshow(wc)
plt.axis("off")
plt.savefig("result.png", dpi=300, bbox_inches='tight')


常见问题解决

  1. 中文显示方块

    • 确保font_path指向正确的中文字体文件(如simhei.ttf
    • 在系统字体目录查找可用字体:import matplotlib.font_manager; print(font_manager.findfont('SimHei'))
  2. 词云形状不匹配

    • 蒙版图片需使用纯黑背景(RGB(0,0,0)),白色区域将显示词云
  3. 性能优化

    • 大文本处理时添加jieba.enable_parallel(4)启用多核分词

通过此流程,可快速实现文本关键词提取和可视化分析,适用于舆情监控、论文分析等场景。进阶方向可考虑结合TF-IDF权重优化词云显示效果。

Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐