总结
豆包 AI 助手文章总结

Python制作词云的代码怎么写

碧海醫心
发布: 2025-04-16 18:52:11
原创
462人浏览过

本文将为您详细解读如何用python编写生成词云的代码,希望您阅读完后能有所收益。

导入所需的库

import numpy as np
import pandas as pd
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
登录后复制

读取文本数据

text = "你的文本数据"
登录后复制

创建词云对象

# 设定词云参数
wordcloud = WordCloud(
    width=800,  # 设置宽度
    height=600,  # 设置高度
    background_color="white",  # 背景色设为白色
    stopwords=STOPWORDS,  # 使用预设的停用词列表
    max_words=200,  # 最大显示词数为200
).generate(text)
登录后复制

生成词云图

立即学习Python免费学习笔记(深入)”;

wordcloud.to_file("wordcloud.png")  # 将词云保存为文件
登录后复制

自定义词云形状

# 读取形状图像
mask = np.array(Image.open("shape.png"))
<h1>生成带有特定形状的词云对象</h1><p>wordcloud = WordCloud(
width=800,
height=600,
background_color="white",
mask=mask,  # 使用形状作为掩码
max_words=200,
).generate(text)</p><h1>生成词云</h1><p>wordcloud.to_file("wordcloud_shaped.png")
登录后复制

应用字体和颜色

# 设定字体
font_path = "path/to/font.ttf"
wordcloud = WordCloud(
font_path=font_path,
).generate(text)
wordcloud.to_file("wordcloud_with_font.png")</p><h1>设定颜色图</h1><p>color_map = "path/to/color_map.png"
wordcloud = WordCloud(
colormap=color_map,
).generate(text)
wordcloud.to_file("wordcloud_with_color_map.png")
登录后复制

处理非英语文本

# 对非英语文本使用自定义停用词列表
stopwords = ["word1", "word2", "word3"]
wordcloud = WordCloud(
stopwords=stopwords,
).generate(text)
wordcloud.to_file("wordcloud_with_custom_stopwords.png")</p><h1>使用正则表达式过滤非英语单词</h1><p>import re
regex = r"[^ws]"
text = re.sub(regex, "", text)
wordcloud = WordCloud().generate(text)
wordcloud.to_file("wordcloud_non_english.png")
登录后复制

高级选项

  • collocations: 允许词对同时显示
  • max_font_size: 设定最大字体大小
  • scale: 调整词云的缩放比例
  • contour_width: 设定轮廓宽度
  • contour_color: 设定轮廓颜色

以上内容详细介绍了如何用Python编写生成词云的代码。如需更多相关内容,请访问编程学习网查看其它文章!

Python制作词云的代码怎么写

以上就是Python制作词云的代码怎么写的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号