Search code examples
pythonwordcloud2

about OS error cannot find source in Python


I am a Korean who just started learning python now. I was doing wordcloud with Korean text. I think I did everything I was taught. But I got this error that I cannot resolve. please help me.

from wordcloud import WordCloud
from collections import Counter
from konlpy.tag import Okt

this is the input

text=''
with open("./res/대한민국헌법.txt", encoding="utf-8") as f:

text = f.read()

nlp =Okt()
nouns =nlp.nouns(text)
# print(nouns)
# print("-" * 30)

words=[]
for n in nouns:
    if len(n) >1:
        words.append(n)
# print(words)
print("-" * 30)

#Counter 객체를 통해 리스트 원소들의 빈도수 계산
count =Counter(words)

most=count.most_common(100)
# print(most)
print("-" * 30)

tags={}
for t in most:
    n, c= t
    tags[n]=c

print(tags)

wc= WordCloud(font_path="NanumGothic", width=1200, height=800,
                scale=2.0, max_font_size=250)

wc.generate_from_frequencies(tags) # <- this is where I got the error from
wc.to_file("대한민국헌법-주요단어.png")

This is the output

Traceback (most recent call last): File "D:\hyeokjun\01-파이썬기초, 데이터 시각화\09-데이터시각화 -가로막대+파이+산점도그래프+워드클라우드\파이썬09강\파이썬09강\section09\01.numeric.py", line 40, in wc.generate_from_frequencies(tags) File "C:\Users\newjh\AppData\Local\Programs\Python\Python37\lib\site-packages\wordcloud\wordcloud.py", line 496, in generate_from_frequencies font = ImageFont.truetype(self.font_path, font_size) File "C:\Users\newjh\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 648, in truetype return freetype(font) File "C:\Users\newjh\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 645, in freetype return FreeTypeFont(font, size, index, encoding, layout_engine) File "C:\Users\newjh\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 194, in init font, size, index, encoding, layout_engine=layout_engine OSError: cannot open resource [Finished in 5.9s]


Solution

  • It seems the font cannot be retrieved. Try copying the font "NanumGothic" into your project folder or update the font_path="NanumGothic" in the following line to point to the correct font file:

    wc= WordCloud(font_path="/path/to/fontfile", width=1200, height=800,
                    scale=2.0, max_font_size=250)