使用Python生成二元组词云的实现方法及代码相关咨询
嘿,我把你从Stack Overflow复用的词云代码整理成完整可运行的版本啦,还补全了缺失的部分,直接就能用哦~
使用Python WordCloud库从文本文件生成词云
第一步先确认安装依赖库(没装过的话执行这条命令):
pip install wordcloud matplotlib完整可运行代码:
import matplotlib.pyplot as plt from wordcloud import WordCloud, STOPWORDS import random # 自定义词云颜色生成函数,生成暖色调随机亮度的文字 def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None): h = int(360.0 * 45.0 / 255.0) s = int(100.0 * 255.0 / 255.0) l = int(100.0 * float(random_state.randint(60, 120)) / 255.0) return "hsl({}, {}%, {}%)".format(h, s, l) # 读取你的文本文件内容,记得替换成实际文件路径哦 with open("你的文本文件路径.txt", "r", encoding="utf-8") as f: text_content = f.read() # 配置并生成词云 wordcloud = WordCloud( stopwords=STOPWORDS, # 过滤默认的停用词(比如"the"、"and"这类无意义词) background_color="white", # 词云背景色,可改成"black"等 width=1200, # 词云画布宽度 height=800, # 词云画布高度 color_func=random_color_func, # 应用自定义的颜色规则 random_state=42 # 固定随机种子,保证每次生成的词云布局一致 ).generate(text_content) # 展示生成的词云 plt.figure(figsize=(12, 8)) plt.imshow(wordcloud, interpolation="bilinear") plt.axis("off") # 隐藏坐标轴,让词云更美观 plt.show()小提示:
- 如果你的文本是中文,记得在
WordCloud参数里添加font_path="你的中文字体路径.ttf"(比如系统里的黑体、宋体路径),不然会出现乱码 - 可以根据需求调整参数,比如用
max_words=200限制显示的最大词数,或者自定义stopwords集合添加更多要过滤的专属停用词
- 如果你的文本是中文,记得在
内容的提问来源于stack exchange,提问作者DreamerP




