python中word cloud库异型词云图代码
时间: 2023-12-04 20:11:38 浏览: 83
【Python实战应用案例代码】-wordcloud词云图绘制.zip
以下是一个简单的Python代码示例,使用WordCloud库生成异型词云图:
```python
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
# 读取文本文件
text = open('your_text_file.txt', 'r').read()
# 读取图像文件
mask = np.array(Image.open('your_image_file.png'))
# 设置停用词列表
stopwords = set(STOPWORDS)
stopwords.update(["said", "will", "one", "now", "well", "man", "may", "us", "much", "say", "yet", "make"])
# 设置WordCloud对象
wc = WordCloud(background_color="white", max_words=2000, mask=mask, stopwords=stopwords, contour_width=3, contour_color='steelblue')
# 生成词云图
wc.generate(text)
# 提取图像颜色
image_colors = ImageColorGenerator(mask)
# 显示词云图
plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
plt.axis('off')
plt.show()
```
需要注意的是,上述代码需要先安装相关库,比如wordcloud、matplotlib、numpy和Pillow。
阅读全文