登录
首页 >  文章 >  python教程

Python词云制作详解与代码示例

时间:2025-05-16 11:45:36 180浏览 收藏

本文详细介绍了如何使用Python生成词云的代码。首先,我们导入了必要的库,如numpy、pandas和wordcloud等。接着,通过读取文本数据并设置词云参数,如宽度、高度和背景颜色等,生成了基本的词云图。此外,文章还展示了如何自定义词云形状、应用特定字体和颜色,以及处理非英语文本的方法。最后,介绍了一些高级选项,如词对显示、最大字体大小和轮廓设置等,帮助读者全面掌握词云生成技术。

本文将为您详细解读如何用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)

生成词云图

wordcloud.to_file("wordcloud.png")  # 将词云保存为文件

自定义词云形状

# 读取形状图像
mask = np.array(Image.open("shape.png"))

生成带有特定形状的词云对象

wordcloud = WordCloud( width=800, height=600, background_color="white", mask=mask, # 使用形状作为掩码 max_words=200, ).generate(text)

生成词云

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")

设定颜色图

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")

使用正则表达式过滤非英语单词

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制作词云的代码怎么写

今天带大家了解了的相关知识,希望对你有所帮助;关于文章的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>