nltk.probability.FreqDistのplotが動くようになるまで
まずnltkの導入。手元の環境はsnow leopard + pythonbrew + python2.7.1です。nltkはpython2.7をサポートしていないようですが、特に問題なくインストールできました。
% easy_install http://nltk.googlecode.com/files/nltk-2.0.1rc1-py2.6.egg
続いてnltkのbookをダウンロードします。
import nltk
nltk.download()
GUIが起動するので、bookを選択してDownloadをクリックします。これでとりあえずnltkの導入は完了です。
次に、matplotlibの導入でもつまづいたのでメモ。手元の環境でeasy_install matplotlibを実行すると、
src/_image.cpp:953: error: ‘png_infopp_NULL’ was not declared in this scope error: Setup script exited with error: command 'gcc' failed with exit status 1
と出てしまってインストールに失敗します。これを解決するには、src/_image.cppに以下のようなマクロを追加します。
参考: http://d.hatena.ne.jp/knaka20blue/20100524/1274693694
#define png_infopp_NULL (png_infopp)NULL #define int_p_NULL (int*)NULL
このマクロの追加で無事インストールできました。流れは以下の通りです。
% easy_install --build-directory . matplotlib # error % cd matplotlib % vim src/_image.cpp # マクロの追加 % easy_install .
これで無事matplotlibをインストールできたのですが、このままでは使えない場合があります。nltkはnumpy1.1以降を必須としているのですが、numpyのバージョンが新しすぎる場合には問題が起きます。私の環境ではnumpy1.6.0ですが、このバージョンでは問題が起きました。これを解決するにはmatplotlibのソースを少し修正します。
% cd ~/.pythonbrew/pythons/Python2.7.1/lib/python2.7/site-packages/matplotlib-0.91.1-py2.7-macosx-10.4-x86_64.egg/matplotlib/numerix % vim ma/__init__.py % vim npyma/__init__.py
両ファイルとも、以下のように修正します。
参考: http://d.hatena.ne.jp/dekaduki/20110207/1297086149
numpy.core.ma(修正前) -> numpy.ma(修正後)
以上でようやくnltk.probability.FreqDistのplotが使えるようになりました。
import nltk file = open('data.txt') rawtext = file.read() tokens = nltk.word_tokenize(rawtext) text = nltk.Text(tokens) freqDist = nltk.FreqDist(text) freqDist.plot(100, cumulative=True)