接着我们编写一个画词云图的函数,该函数中的功能包括文本预处理、文本分词、去除停用词、词频统计、画出top10词频条形图、画出词云图。
时间: 2025-03-15 20:18:16 浏览: 15
创建包含文本预处理、分词、去除停用词、词频统计及生成 Top10 条形图和词云图的 Python 函数
以下是实现上述功能的一个综合函数,涵盖了文本预处理、分词、去停用词、词频统计以及绘制 Top10 条形图和词云图的功能。
综合函数代码
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from collections import Counter
import pandas as pd
def text_processing_and_visualization(text, stopwords_path=None):
"""
对输入文本进行预处理并生成词频统计、Top10条形图和词云图。
参数:
text (str): 输入的原始文本数据。
stopwords_path (str): 停用词表路径,默认为 None。
返回:
DataFrame: 包含词语及其频率的数据框。
"""
# 加载停用词列表
if stopwords_path is not None:
with open(stopwords_path, 'r', encoding='utf-8') as f:
stopwords = set(f.read().splitlines())
else:
stopwords = set()
# 分词操作
words = jieba.lcut(text)
# 过滤掉停用词
filtered_words = [word for word in words if word.strip() and word not in stopwords]
# 计算词频
word_counts = Counter(filtered_words)
word_freq_df = pd.DataFrame(word_counts.items(), columns=['Word', 'Frequency']).sort_values(by='Frequency', ascending=False).reset_index(drop=True)
# 输出前 10 的高频词汇
top_10_words = word_freq_df.head(10)
# 绘制 Top10 高频词汇条形图
plt.figure(figsize=(10, 6))
plt.bar(top_10_words['Word'], top_10_words['Frequency'], color='skyblue')
plt.title('Top 10 High-Frequency Words')
plt.xlabel('Words')
plt.ylabel('Frequency')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# 生成词云图
wc = WordCloud(font_path="simhei.ttf", background_color="white", max_words=200, width=800, height=400)
wc.generate_from_frequencies(word_counts)
plt.figure(figsize=(10, 6))
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.title('Word Cloud Visualization')
plt.show()
return word_freq_df
功能说明
- 加载停用词: 如果提供了
stopwords_path
路径,则会加载该文件中的停用词集合[^1]。 - 分词: 使用
jieba.lcut()
方法对文本进行精确模式分词。 - 过滤停用词: 将分词后的结果与停用词集合作比较,移除其中的无意义词汇。
- 计算词频: 利用
collections.Counter
统计每个单词出现的次数,并将其转换为 Pandas 数据框以便后续分析。 - 绘制 Top10 条形图: 展示排名前十的高频词汇及其对应的频率分布情况。
- 生成词云图: 使用
wordcloud.WordCloud
类构建基于词频的可视化图像[^2]。
示例调用
假设有一个简单的中文文本字符串:
text = """自然语言处理是一门充满挑战性的学科。它涉及计算机科学、人工智能等多个领域,
并致力于让机器理解人类的语言。通过学习这门课程,你可以掌握许多实用技能。"""
# 停用词表路径(如果存在)
stopwords_path = "stopwords.txt"
result_df = text_processing_and_visualization(text, stopwords_path=stopwords_path)
print(result_df.head(10)) # 打印前 10 行的结果
注意事项
- 若未提供停用词表路径 (
stopwords_path
),则默认不执行停用词过滤。 - 在生成词云时需指定字体文件路径(如
"simhei.ttf"
),以支持显示中文字符。
相关推荐


















