python词云图红楼梦
时间: 2023-10-13 09:20:49 浏览: 51
好的,以下是生成红楼梦词云图的Python代码:
```python
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取红楼梦文本文件
with open('hongloumeng.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba对文本进行分词
words = jieba.cut(text)
# 将分词结果转换为字符串
words_str = ' '.join(words)
# 生成词云图
wc = WordCloud(font_path='simhei.ttf', background_color='white', max_words=2000, width=800, height=600)
wc.generate(words_str)
# 保存词云图
wc.to_file('hongloumeng_wordcloud.png')
# 显示词云图
plt.imshow(wc)
plt.axis('off')
plt.show()
```
其中,`hongloumeng.txt`为红楼梦的文本文件,`simhei.ttf`为中文字体文件。生成的词云图将保存为`hongloumeng_wordcloud.png`文件,并且会显示在Python窗口中。
相关问题
词云图红楼梦 python代码
以下是用 Python 生成红楼梦词云图的代码:
```python
import jieba
from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt
from PIL import Image
# 读取文本文件
with open('hongloumeng.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用 jieba 进行分词
words = jieba.cut(text)
words = ' '.join(words)
# 读取红楼梦的图片
image = Image.open('hongloumeng.jpg')
mask = np.array(image)
# 生成词云图
wc = WordCloud(font_path='msyh.ttc', mask=mask, background_color='white', max_words=5000, max_font_size=80)
wc.generate(words)
# 基于图片颜色生成词云图的颜色
image_colors = ImageColorGenerator(mask)
wc.recolor(color_func=image_colors)
# 保存词云图
wc.to_file('hongloumeng_wordcloud.jpg')
# 显示词云图
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
```
需要注意的是,为了能够正确显示中文,需要在代码中指定字体文件,如上面的代码中的 `font_path='msyh.ttc'`。此外,还需要准备一张红楼梦的图片,用于生成词云图的形状。在代码中,我们使用了 Pillow 库的 `Image.open()` 函数来读取图片,并将其转换为 NumPy 数组用于生成词云图的形状。最后,调用 `WordCloud` 类的 `recolor()` 方法可以基于图片颜色重新生成词云图的颜色,使得词云图更加美观。
pycharm词云图红楼梦
以下是在PyCharm中绘制红楼梦词云图的步骤:
1.安装必要的库
```shell
pip install jieba
pip install wordcloud
pip install imageio
```
2.导入必要的库
```python
import jieba
from wordcloud import WordCloud, ImageColorGenerator
import imageio
import matplotlib.pyplot as plt
```
3.读取红楼梦文本文件
```python
with open('红楼梦.txt', 'r', encoding='utf-8') as f:
text = f.read()
```
4.使用jieba库进行分词
```python
words = jieba.cut(text)
```
5.将分词结果转换为字符串
```python
words_str = ' '.join(words)
```
6.读取背景图片
```python
mask = imageio.imread('hongloumeng.jpg')
```
7.生成词云图
```python
wc = WordCloud(background_color='white', mask=mask, font_path='msyh.ttc', max_words=2000, max_font_size=200, random_state=42)
wc.generate(words_str)
```
8.根据图片生成颜色
```python
image_colors = ImageColorGenerator(mask)
```
9.绘制词云图
```python
plt.figure(figsize=(10, 10))
plt.imshow(wc.recolor(color_func=image_colors), interpolation='bilinear')
plt.axis('off')
plt.show()
```