python之OSError: cannot open resource错误+解决方案
错误背景
博主在用jieba库对个性签名进行分词,然后再用WordCloud生成词云时,发生了如下错误。
错误类型
OSError: cannot open resource
问题代码
def create_wc(words_list):
res_path = os.path.abspath('./esource')
words = ' '.join(words_list)
# 背景图形
back_pic = numpy.array(Image.open("%s/china1.png" % res_path))
stopwords = set(STOPWORDS)
stopwords = stopwords.union(set(['class', 'span', 'emoji', 'emoji', 'emoji1f388', 'emoji1f604', 'emoji1f436']))
wc = WordCloud(
# 设备背景颜色
background_color="white",
margin=0,
# 设置字体,不设置就会出现乱码
font_path='%s/hanyiqihei.ttf' % res_path,
# 词云形状
mask=back_pic,
# 最大字号
max_font_size=70,
stopwords=stopwords).generate(words)# 产生词云
# image_colors = ImageColorGenerator(back_pic)
# 显示词云图片
plt.imshow(wc)
# plt.imshow(wc.recolor(color_func=image_colors))
plt.axis('off')
plt.show()
# 保存图片
wc.to_file('test.jpg')
解决方案
将
font_path='%s/hanyiqihei.ttf' % res_path,改成font_path='hanyiqihei.ttf'
说明
hanyiqihei.ttf是自己的汉仪旗黑字体,只要把font_path要设置,不然会有乱码出现。
汉仪旗黑字体