用Wordcloud生成中文词云时遇到的问题

用Wordcloud生成中文词云时遇到的问题

import jieba
import wordcloud

f= open ('ciyun.txt',encoding='utf-8')
t=f.read()
f.close()
ls=jieba.lcut(t)
txt=" ".join(ls)

w=wordcloud.WordCloud(font_path="微软雅黑粗体.ttf",width=1000,height=700,background_color="white")
w.generate(txt)
w.to_file("wordcloud.png")


Traceback (most recent call last):
  File "E:\python code\政府工作报告词云.py", line 11, in <module>
    w.generate(txt)
  File "D:\python3\lib\site-packages\wordcloud\wordcloud.py", line 605, in generate
    return self.generate_from_text(text)
  File "D:\python3\lib\site-packages\wordcloud\wordcloud.py", line 587, in generate_from_text
    self.generate_from_frequencies(words)
  File "D:\python3\lib\site-packages\wordcloud\wordcloud.py", line 426, in generate_from_frequencies
    max_font_size=self.height)
  File "D:\python3\lib\site-packages\wordcloud\wordcloud.py", line 473, in generate_from_frequencies
    font = ImageFont.truetype(self.font_path, font_size)
  File "D:\python3\lib\site-packages\PIL\ImageFont.py", line 280, in truetype
    return FreeTypeFont(font, size, index, encoding, layout_engine)
  File "D:\python3\lib\site-packages\PIL\ImageFont.py", line 145, in __init__
    layout_engine=layout_engine)
OSError: cannot open resource

在生成中文词云时老是跳出这个问题,而且这段代码使我直接拿的老师上课时讲的。自己在网上搜索了很久,都没能找到解答,最后只能将程序中的代码一行一行的删除,看时什么位置出现的这个bug,当删到font_path="微软雅黑粗体.ttf"这部分时,bug才消失,这才明白原来是自己没有下载对应的字体文件。上课老师也是没有讲,我还天真的以为字体文件是Python平台自带的,果然是我太天真了,在网上下载了一个ttf文件就运行成功了。

你可能感兴趣的:(Python入门)