import jieba import wordcloud from imageio import imread import cv2 stopwords=['的','了','也','但','年','月','日','在','个','是'] mask=cv2.imread('C:/Users/86147/Desktop/新建文件夹/微信图片_20230606222133.jpg', 0) ret, binary = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY) f=open("C:\Users\86147\Desktop\新建文件夹\科技巨头进一步领涨,当下美股太像“互联网泡沫”时期了-20230606-221833.txt", "r", encoding="GB2312") t=f.read() f.close() ls=[word for word in jieba.lcut(t) if word not in stopwords] txt=" ".join(ls) wc=wordcloud.WordCloud(width=1000, height=700,\ background_color = "white", mask = binary,\ font_path = "msyh.ttc", stopwords=stopwords) wc.generate(txt) wc.to_file("mywc.png")这个代码为什么不能按照指定的图片生成词云呢?
时间: 2024-01-30 07:04:14 浏览: 76
有几个可能的原因:
1. 读取的图片路径不正确:请确保代码中的图片路径是正确的,即图片文件存在且路径正确。可以尝试使用绝对路径或者相对路径。
2. 图片格式不正确:代码中使用的是jpg格式的图片,但是有些jpg图片并不支持灰度模式,需要先将图片转换成灰度模式。
3. 图片尺寸太小:请确保图片的宽度和高度足够大,以便生成清晰的词云图像。可以尝试调整代码中的width和height参数。
4. 字体文件不存在或路径不正确:请确保代码中指定的字体文件存在且路径正确。
5. 其他问题:还有可能是其他原因导致生成词云失败,可以尝试检查代码中的语法错误或者调试代码。
相关问题
import jieba from wordcloud import WordCloud
这段代码有语法错误,正确的写法应该是:
```python
import jieba
from wordcloud import WordCloud
```
首先需要导入 jieba 模块,然后再从 wordcloud 模块中导入 WordCloud 类。这样就可以在代码中使用 WordCloud 类来生成词云了。
import jieba import wordcloud import imageio mask = imageio.imread('C:/Users/Febird/Desktop/1.png') #设定一个词云背景 with open('C:/Users/Febird/Desktop/傲世.txt', encoding='utf-8') as f: t = f.read() # 打开需要制作词云图的文件 ls = jieba.lcut(t) txt = " ".join(ls) # 将文章中的词组提出来 stopwords_file = open('C:/Users/Febird/Desktop/stopWord.txt', 'r', encoding='utf-8') stopwords = [(words.strip()) for words in stopwords_file.readlines()] w = wordcloud.WordCloud(width=4000, height=4000, stopwords=stopwords, font_path="msyh.ttc", colormap='hot', background_color='pink', mask=mask) # 定义一个词云 w.generate(txt) #生成词云 w.to_file(r'C:/Users/Febird/Desktop/test_3.png') #将词组变量txt导入词云对象w中并保存 添加代码 完成排名前五十个词的词云
在代码中添加以下部分可以完成排名前五十个词的词云:
```
from collections import Counter
# 统计词频
words_count = Counter(ls)
# 获取词频前50的词及其频次
top50_words = words_count.most_common(50)
# 将排名前50的词转换为一个字符串
top50_str = ""
for word, count in top50_words:
top50_str += (word + " ") * count
# 生成词云
w.generate(top50_str)
```
完整代码如下:
```
import jieba
import wordcloud
import imageio
from collections import Counter
mask = imageio.imread('C:/Users/Febird/Desktop/1.png')
with open('C:/Users/Febird/Desktop/傲世.txt', encoding='utf-8') as f:
t = f.read()
ls = jieba.lcut(t)
txt = " ".join(ls)
stopwords_file = open('C:/Users/Febird/Desktop/stopWord.txt', 'r', encoding='utf-8')
stopwords = [(words.strip()) for words in stopwords_file.readlines()]
w = wordcloud.WordCloud(width=4000, height=4000,
stopwords=stopwords,
font_path="msyh.ttc",
colormap='hot',
background_color='pink',
mask=mask)
# 统计词频
words_count = Counter(ls)
# 获取词频前50的词及其频次
top50_words = words_count.most_common(50)
# 将排名前50的词转换为一个字符串
top50_str = ""
for word, count in top50_words:
top50_str += (word + " ") * count
# 生成词云
w.generate(top50_str)
w.to_file(r'C:/Users/Febird/Desktop/test_3.png')
```
阅读全文