import jieba import numpy import numpy as np from PIL import Image from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt with open("comments.txt","r",encoding="utf-8") as f: comments = f.read() words = jieba.cut(comments) stopwords = set(STOPWORDS) stopwords.add('腾讯') stopwords.add('游戏') filtered_words = [] for word in words: if word not in stopwords: filtered_words.append(word) mask = np.array(Image.open("mask.png")) cloud = WordCloud( font_path="C:\Windows\Fonts\simsun.ttc", background_color="white", mask=mask ).generate(" ".join(filtered_words)) cloud.to_file("词云.png") print("词云绘制成功")这个代码运行结果为什么是错误
时间: 2024-02-14 10:06:45 浏览: 146
python词云库wordCloud使用方法详解(解决中文乱码)
这段代码缩进有误,导致程序运行时会出现语法错误。代码中的 WordCloud 的 generate 方法和 to_file 方法应该在 for 循环外面,否则会导致生成多个词云图片。除此之外,代码中使用的路径需要注意转义符的使用。修改后的代码如下所示:
```python
import jieba
import numpy as np
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
with open("comments.txt","r",encoding="utf-8") as f:
comments = f.read()
words = jieba.cut(comments)
stopwords = set(STOPWORDS)
stopwords.add('腾讯')
stopwords.add('游戏')
filtered_words = []
for word in words:
if word not in stopwords:
filtered_words.append(word)
mask = np.array(Image.open("mask.png"))
cloud = WordCloud(
font_path=r"C:\Windows\Fonts\simsun.ttc",
background_color="white",
mask=mask,
stopwords=stopwords
).generate(" ".join(filtered_words))
cloud.to_file("词云.png")
print("词云绘制成功")
```
注意,代码中的 font_path 路径需要使用原始字符串标记 r,避免转义符被 Python 解释器处理。此外,WordCloud 对象的 stopwords 属性可以直接传入 stopwords 变量,这样就不需要在循环中判断单词是否在停用词列表中了。
阅读全文