DeepSeek-CJK-patch, Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", Ubuntu, Cantarell, "Helvetica Neue", Oxygen, "Open Sans", sans-serif;font-size: 16.002px;font-style: normal;font-variant-ligatures: normal;font-variant-caps: normal;letter-spacing: normal;orphans: 2;text-align: start;text-indent: 0px;text-transform: none;widows: 2;word-spacing: 0px;-webkit-text-stroke-width: 0px;white-space: normal;background-color: rgb(255, 255, 255);text-decoration-thickness: initial;text-decoration-style: initial;text-decoration-color: initial;"> 词云图(Word Cloud)是一种通过视觉化方式展示文本数据的图形表示,它将文本中的关键词按照重要度进行排版,重要的词汇会以更大、更突出的字体显示,相反则较小,用户可根据需求设置显示重要的TopK个词汇组成词云。词云图常用于快速捕捉文本的主题、趋势或高频、重要词汇。

1.所需工具包及安装
wordcloud 词云库
GitHub:https://github.com/amueller/word_cloud
Python 词云生成库,支持自定义字体、颜色、形状等。
jieba 分词(中文词云分词、关键词抽取)
GitHub:https://github.com/fxsjy/jieba
中文分词工具,支持精确模式、全模式、搜索引擎模式等。
!pip install jieba
!pip install wordcloud
#运行无误,工具包正确安装import jiebaimport wordcloud
工具包安装常见错误:

2.停用词
停用词(Stop Words)是在自然语言处理(NLP)和文本分析中被忽略的常见词汇,通常因为它们本身没有实际含义,或对文本的语义贡献很小。这些词通常是高频出现的功能词,比如介词、连词、代词等。
常见的停用词例子
中文:的、了、和、是、在、我、你、这、那……
英文:the, a, an, and, in, on, at, is, are, of, to…
停用词的作用
提高处理效率:减少计算量,加快文本处理速度。
提升分析质量:过滤掉无意义的词,让算法更关注关键内容(如关键词、情感词等)。
适用于多种任务:如搜索引擎、文本分类、情感分析、机器翻译等。
停用词的缺点
在某些情况下可能影响语义,比如:
“To be or not to be”(莎士比亚名句)如果去掉停用词,会丢失重要信息。
中文“不是”如果去掉“不”,意思完全相反。
如何使用停用词?
NLP工具库(如NLTK、spaCy、中文的jieba)通常内置停用词列表,可以直接调用。
自定义停用词表:根据任务需求增删停用词。
例如,在Python中使用NLTK去除英文停用词:
from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenizetext = "This is an example sentence showing off stop words."stop_words = set(stopwords.words("english"))words = word_tokenize(text)filtered_words = [word for word in words if word.lower() not in stop_words]print(filtered_words)# 输出:["example", "sentence", "showing", "stop", "words", "."]
import jiebatext = "这是一个用来演示停用词的例子。"stopwords = ["的", "是", "一个", "用来"]words = jieba.lcut(text)filtered_words = [word for word in words if word not in stopwords]print(filtered_words)#输出:["这", "演示", "停用词", "例子", "。"]

sentence :为待提取的文本 topK:为返回几个 TF/IDF 权重最大的关键词,默认值为 20 withWeight :为是否一并返回关键词权重值,默认值为 False allowPOS :仅包括指定词性的词,默认值为空,即不筛选,也可设置词性进行筛选

from sklearn.feature_extraction.text import TfidfVectorizer
X_test = ["互联网 技术 报告","人工智能 技术 报告"]
tfidf=TfidfVectorizer()
weight=tfidf.fit_transform(X_test).toarray()
word=tfidf.get_feature_names()
print (weight)
for i in range(len(weight)):
print (u"第", i, u"篇文章的tf-idf权重特征")
for j in range(len(word)):
print (word[j], weight[i][j])

corpus = ["This is the first document.", "This document is the second document.", "And this is the third one.", "Is this the first document?"] #初始化 vector = TfidfVectorizer()#tf-idf计算 tfidf = vector.fit_transform(corpus) #直接打印,得到的是一个稀疏矩阵,第1位表示文档编号,第二位代表词的编号 print(tfidf) (0, 1) 0.46979138557992045 (0, 2) 0.5802858236844359 (0, 6) 0.38408524091481483 (0, 3) 0.38408524091481483 (0, 8) 0.38408524091481483 (1, 5) 0.5386476208856763 (1, 1) 0.6876235979836938 (1, 6) 0.281088674033753 (1, 3) 0.281088674033753 (1, 8) 0.281088674033753 (2, 4) 0.511848512707169 (2, 7) 0.511848512707169 (2, 0) 0.511848512707169 (2, 6) 0.267103787642168 (2, 3) 0.267103787642168 (2, 8) 0.267103787642168 (3, 1) 0.46979138557992045 (3, 2) 0.5802858236844359 (3, 6) 0.38408524091481483 (3, 3) 0.38408524091481483 (3, 8) 0.38408524091481483
vector.vocabulary_ {"this": 8, "is": 3, "the": 6, "first": 2, "document": 1, "second": 5, "and": 0, "third": 7, "one": 4}
(0, 1) 0.46979138557992045 document
(0, 2) 0.58028582368443590 first
(0, 6) 0.38408524091481483 the
(0, 3) 0.38408524091481483 is
(0, 8) 0.38408524091481483 this
document:log((1+N)/(1+N(document)))+1= log((1+4)/(1+3))+1 = 1.2231435first :log((1+N)/(1+N(first)))+1 = log((1+4)/(1+2))+1 = 1.5108256the :log((1+N)/(1+N(the )))+1 = log((1+4)/(1+4))+1 = 1.0is :log((1+N)/(1+N(is )))+1 = log((1+4)/(1+4))+1 = 1.0this :log((1+N)/(1+N(this)))+1 = log((1+4)/(1+4))+1 = 1.0


import jieba
import jieba.analyse
import networkx as nx
from collections import defaultdict
def textrank_keywords(text, top_k=5, lang="zh"):
"""
TextRank关键词提取
:param text: 输入文本
:param top_k: 返回关键词数量
:param lang: 语言(zh/en)
"""
# 中文处理
if lang == "zh":
# 使用jieba的TextRank实现
keywords = jieba.analyse.textrank(
text,
topK=top_k,
withWeight=True, # 返回权重
allowPOS=("n", "vn", "v") # 仅提取名词、动名词、动词
)
return dict(keywords)
# 英文处理(简单实现)
elif lang == "en":
# 分词并过滤停用词
words = [word.lower() for word in text.split()
if word.isalpha() and len(word) > 2]
# 构建共现窗口
window_size = 3
co_occur = defaultdict(int)
for i in range(len(words)):
for j in range(i+1, min(i+window_size, len(words))):
co_occur[(words[i], words[j])] += 1
# 构建图并计算权重
graph = nx.Graph()
for (w1, w2), count in co_occur.items():
graph.add_edge(w1, w2, weight=count)
# PageRank计算
ranks = nx.pagerank(graph)
return dict(sorted(ranks.items(), key=lambda x: x[1], reverse=True)[:top_k])
# 示例中文文本
zh_text = "自然语言处理是人工智能的重要分支,致力于让计算机理解人类语言。深度学习技术在自然语言处理中取得了显著进展。"
print("中文关键词:", textrank_keywords(zh_text, lang="zh"))
# 示例英文文本
en_text = "Artificial intelligence is transforming industries. Machine learning and deep learning are key technologies in AI."
print("英文关键词:", textrank_keywords(en_text, lang="en"))


中文字体:需指定支持中文的字体路径(如
simhei.ttf
),否则会乱码。
下载字体后,将路径传递给
font_path
参数。分词效果:可通过
jieba.add_word()
添加自定义词典,优化专业术语分词。形状掩码:图片需为黑白背景,黑色部分会被视为填充区域。如案例中的蒙版图片heart.png文件如下:
在线工具:WordArt.com、TagCrowd、WordClouds.com。

#英文词云图
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt#绘制图像的模块
import jieba.analyse as anls# 关键词提取
from collections import Counter
import PIL.Image as image
import numpy as np
#打开模板图片
mask=np.array(image.open("heart.png"))
#读取文本,novel.txt为红楼梦的英文介绍
text=open("novel.txt","r",encoding="utf-8").read()
text_split_no=jieba.cut(text,cut_all=True)
text_split_no_str=" ".join(text_split_no)
#list类型分为str
#基于tf-idf提取关键词
print("基于TF-IDF提取关键词结果:")
keywords=[]
for x,w in anls.extract_tags(text_split_no_str,topK=80,withWeight=True):
keywords.append(x)
#前topK个关键词组成的list
keywords=" ".join(keywords)
#转为str
print(keywords)
#画词云
#设置背景、长宽
wordcloud=WordCloud(font_path="C:/Windows/Fonts/simfang.ttf",background_color="white",mask=mask,width=2000,height=1880).generate(keywords)
#keywords为字符串类型
plt.imshow(wordcloud,interpolation="bilinear")
plt.axis("off")
plt.show()
wordcloud.to_file("hlm.png")



# coding: utf-8
import jieba
import cv2
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt
back_color = cv2.imread("heart.png") # 解析该图片
wc = WordCloud(background_color="white", # 背景颜色
max_words=1000, # 最大词数
mask=back_color, # 以该参数值作图绘制词云,这个参数不为空时,width和height会被忽略
max_font_size=100, # 显示字体的最大值
stopwords=STOPWORDS.add("page"), # 使用内置的屏蔽词,再添加"苟利国"
font_path="SIMLI.TTF", # 解决显示口字型乱码问题,可进入C:/Windows/Fonts/目录更换字体
random_state=42, # 为每个词返回一个PIL颜色
# width=1000, # 图片的宽
# height=860 #图片的长
)
# WordCloud各含义参数请点击 wordcloud参数
# 添加自己的词库分词,比如添加"怡红公子"到jieba词库后,该词就作为一个整体输出
jieba.add_word("石头记")
# 打开词源的文本文件
text = open("hl.txt","r",encoding="utf-8").read()
# 该函数的作用就是把屏蔽词去掉,使用这个函数就不用在WordCloud参数中添加stopwords参数了
# 把你需要屏蔽的词全部放入一个stopwords文本文件里即可
def stop_words(texts):
words_list = []
word_generator = jieba.cut(texts, cut_all=False) # 返回的是一个迭代器
with open("stopwords.txt","r",encoding="utf-8") as f:
str_text = f.read()
f.close() # stopwords文本中词的格式是"一词一行"
for word in word_generator:
if word.strip() not in str_text:
words_list.append(word)
return " ".join(words_list) # 注意是空格
text = stop_words(text)
wc.generate(text)
# 基于彩色图像生成相应彩色
image_colors = ImageColorGenerator(back_color)
# 显示图片
plt.imshow(wc)
# 关闭坐标轴
plt.axis("off")
# 绘制词云
plt.figure()
plt.imshow(wc.recolor(color_func=image_colors))
plt.axis("off")
# 保存图片
wc.to_file("out.png")
发表评论 取消回复