微信扫码
添加专属顾问
我要投稿
探索Python文本可视化的实用工具,掌握词云图的制作技巧和关键要点。 核心内容: 1. 词云图的定义及在文本分析中的作用 2. Python绘制词云图的完整流程和关键工具包 3. 停用词的概念、作用及在Python中的处理方法
词云图(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)#输出:['这', '演示', '停用词', '例子', '。']
from sklearn.feature_extraction.text import TfidfVectorizerX_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 jiebaimport jieba.analyseimport networkx as nxfrom collections import defaultdictdef 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 = 3co_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文件如下:
#英文词云图import jiebafrom wordcloud import WordCloudimport matplotlib.pyplot as plt#绘制图像的模块import jieba.analyse as anls# 关键词提取from collections import Counterimport PIL.Image as imageimport 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个关键词组成的listkeywords=" ".join(keywords)#转为strprint(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-8import jiebaimport cv2from wordcloud import WordCloud, STOPWORDS, ImageColorGeneratorimport matplotlib.pyplot as pltback_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')
在线工具:WordArt.com、TagCrowd、WordClouds.com。
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业
2025-10-29
初创公司的增长之道:如何让AI主动推荐你的产品?(下)
2025-10-29
AI将所有生意都卷成了创意产业
2025-10-28
ubuntu 本地部署MinerU完成文档解析
2025-10-27
AI浏览器的正确使用姿势是什么?我从Dia的这90+个Skills里找到了一些好场景
2025-10-27
魔笔 AI Chat Builder:让 AI 对话秒变可交互界面
2025-10-20
天猫行业中后台前端研发Agent设计
2025-10-20
告别错别字和退格键!这款AI语音输入法,让你的打字效率倍增(含实测体验)
2025-10-19
AI自动生成工作流,n8n官方出品
2025-08-06
2025-09-17
2025-09-04
2025-09-02
2025-09-15
2025-09-05
2025-08-22
2025-09-18
2025-08-20
2025-10-10