import pickle from os import path import jieba import jieba.analyse import matplotlib.pyplot as plt from wordcloud import WordCloud,STOPWORDS,ImageColorGenerator import sys sys.path.append('C:\\Users\\李肖\\PycharmProjects\\pythonProject\\text.txt') with open('C:\\Users\\李肖\\PycharmProjects\\pythonProject\\text.txt','r',encoding='utf-8')as fin: text=fin.read() background_Image=plt.imread('main.jpg') print('加载图片成功!') '''设置词云样式''' wc = WordCloud(background_color="black", mask=background_Image, font_path='msyh.ttc', max_words=200, stopwords=STOPWORDS, max_font_size=50, random_state=30) wc.generate_from_text(text) print('开始加载文本') plt.imshow(wc) plt.axis('off') plt.show() d=path.dirname(__file__) wc.to_file(path.join(d,"h11.jpg")) print('生成词云成功!')不能运行
时间: 2023-12-06 12:02:44 浏览: 204
这段代码有几个问题,可以尝试以下修改:
1. 将第一行代码改为`import pickle, os`,这是因为你同时引入了`pickle`和`os`两个模块,需要用逗号分隔开。
2. 在第5行代码中,`sys.path.append()`应该加入的是文件所在目录,而不是文件本身,可以将其修改为`sys.path.append('C:\\Users\\李肖\\PycharmProjects\\pythonProject')`。
3. 第17行代码中,`plt.imshow(wc)`和`plt.axis('off')`之间需要加一个换行符,否则会出现一个警告。
修改后的代码如下:
```
import pickle, os
from os import path
import jieba
import jieba.analyse
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import sys
sys.path.append('C:\\Users\\李肖\\PycharmProjects\\pythonProject')
with open('text.txt', 'r', encoding='utf-8') as fin:
text = fin.read()
background_Image = plt.imread('main.jpg')
print('加载图片成功!')
'''设置词云样式'''
wc = WordCloud(background_color="black",
mask=background_Image,
font_path='msyh.ttc',
max_words=200,
stopwords=STOPWORDS,
max_font_size=50,
random_state=30)
wc.generate_from_text(text)
print('开始加载文本')
plt.imshow(wc)
plt.axis('off')
plt.show()
d = path.dirname(__file__)
wc.to_file(path.join(d, "h11.jpg"))
print('生成词云成功!')
```
阅读全文