下記URLを参考にタグクラウドを生成するコードを書いていますが、以下のエラーがでてしまいます。
http://www.randpy.tokyo/entry/python_wordcloud
Fontファイルはちゃんと指定したディレクトリ配下においてあります。python3.6を利用しているのでpathがhome()をもっていないことはなく、単体でテストするとちゃんと関数を呼べてうごきます。
なぜなのかお気づきな方いましたらご教示頂けませんでしょうか?
import csv from janome.tokenizer import Tokenizer import matplotlib matplotlib.use('Agg') from wordcloud import WordCloud from bs4 import BeautifulSoup from collections import Counter, defaultdict from pathlib import Path #名詞だけ抽出、単語をカウント def counter(texts): t = Tokenizer() words_count = defaultdict(int) words = [] for text in texts: tokens = t.tokenize(text) for token in tokens: #品詞から名詞だけ抽出 pos = token.part_of_speech.split(',')[0] if pos == '名詞': words_count[token.base_form] += 1 words.append(token.base_form) return words_count, words with open('./test.txt','r') as f: reader = csv.reader(f, delimiter='\t') texts = [] for row in reader: text = row[0].split('http') texts.append(text[0]) words_count, words = counter(texts) text = ' '.join(words) #word cloud fpath = "/System/Library/Fonts/ヒラギノ丸ゴ ProN W4.ttc" wordcloud = WordCloud(background_color="white", font_path=fpath, width=900, height=500).generate(text) print(fpath) plt.figure(figsize=(15,12)) plt.imshow(wordcloud) plt.axis("off") plt.show()
エラー
t@CL-180042-MAC ~/D/scratper> python3 testtagcloud.py Traceback (most recent call last): File "testtagcloud.py", line 38, in <module> wordcloud = WordCloud(background_color="white", font_path=fpath, width=900, height=500).generate(text) File "/Users/t/.pyenv/versions/3.6.5/lib/python3.6/site-packages/wordcloud-1.5.0.post10+gb79b3d6-py3.6-macosx-10.13-x86_64.egg/wordcloud/wordcloud.py", line 317, in __init__ self.color_func = color_func or colormap_color_func(colormap) File "/Users/t/.pyenv/versions/3.6.5/lib/python3.6/site-packages/wordcloud-1.5.0.post10+gb79b3d6-py3.6-macosx-10.13-x86_64.egg/wordcloud/wordcloud.py", line 100, in __init__ import matplotlib.pyplot as plt File "/Users/t/.pyenv/versions/3.6.5/lib/python3.6/site-packages/matplotlib/pyplot.py", line 32, in <module> import matplotlib.colorbar File "/Users/t/.pyenv/versions/3.6.5/lib/python3.6/site-packages/matplotlib/colorbar.py", line 32, in <module> import matplotlib.contour as contour File "/Users/t/.pyenv/versions/3.6.5/lib/python3.6/site-packages/matplotlib/contour.py", line 18, in <module> import matplotlib.font_manager as font_manager File "/Users/t/.pyenv/versions/3.6.5/lib/python3.6/site-packages/matplotlib/font_manager.py", line 135, in <module> OSXFontDirectories.append(str(Path.home() / "Library/Fonts")) AttributeError: type object 'Path' has no attribute 'home'
あなたの回答
tips
プレビュー