ラベル 自然言語処理 の投稿を表示しています。 すべての投稿を表示
ラベル 自然言語処理 の投稿を表示しています。 すべての投稿を表示

2016年4月9日土曜日

NLTKを使ってみる---『入門 自然言語処理』を読む2---

さて、『NLTKを使ってみる---『入門 自然言語処理』を読む1----』の続きです。

1.3.1が頻度分布の話になっています。その中でもFreqDistがうまくいかなかったので迷いましたが、結局次のように書くことでうまくいきました。

#以下のようなコードを書いて、例えばnlpex.pyなどの名前で保存する。
import nltk
from nltk.book import *
from nltk import *
fdist1=FreqDist(text1)
print(fdist1)
fdist1.plot(50,cumulative=True)
ターミナルにて
hiroshi-no-MacBook-Air:Pro-tr hiroshi$ python3 nlpex.py      #python3 nlpex.pyと打ってreturnを押す。
とすると、次のような画面が出てきます。


上で書いたコードの冒頭のimportに関する部分ですが、自分の読み間違えでなければ、本の中ではimport nltkだけ書けば書けるような雰囲気で書かれています。

実際やってみると、「NameError:name 'FreqDist' is not defined」とかいうエラーが表示されます。本の中では、こういうエラーがでた場合にはnltk.book import *を実行すればいいよとか書いてあります。

なのでさらに追記してfrom nltk.book import *を書いて実行しますがエラーは消えず。実際には、さらに一行追加してfrom nltk import *も書いて上記のようなコードでないと動きません。


分量が少しになってしまいましたが、本の中では区切りがいいので、一旦区切ります。


参考にしたページや文献・書籍
『入門 自然言語処理』

2016年4月5日火曜日

NLTKを使ってみる---『入門 自然言語処理』を読む1----

ずいぶんと前になりますが、『Macでpython3の環境構築7---NLTKのインストール1---』と『Macでpython3の環境構築8---NLTKのインストール2---』でNLTKをインストールしました。

その流れで、『入門 自然言語処理』を読んでみたいと思います。

というのも、この本ではpython2系をベースにして書かれていまして、python3系で動かしてみたいと思ったからです。

慣れている人にとってはpython2からpython3への読み替えもすぐできるのでしょうが、自分はそうではないし、そういう人もいると思うのでpython3で実際に動いたコードを記載しつつ勉強の過程を記録してきたいと思います。

さてこの記事のスタートとしては、『入門 自然言語処理』でいうところの1.1.3、とりあえずNLTKのインストールができたことが確認できたところから始めたいと思います。

本ではインタプリンタ上、つまりテキストファイルにプログラムを書いて保存してターミナルなどのコマンドから実行するのではなく、直接ターミナルなどのコマンドに逐次コードを打っていく方法で進められていますが、ここでは一旦保存する方法で進めていきます。

本ではtext1.concordance(""monstrous")を実行しています。
これは、指定された単語が現れた全ての場所を、その周辺の文章とともに表示します。
下の例で言えば、text1の中から「monstrous」という単語が現れた場所をその周辺の文章とともに表示します。
これをするには以下のようなコードを書きます。

#以下のように書いて、nlpex.pyという名前で保存することにする。
import nltk
from nltk.book import *
print(text1.concordance("monstrous"))

ターミナルにてカレントディレクトリへ移動し、

hiroshi-no-MacBook-Air:Pro-tr hiroshi$ python3 nlpex.py      #python3 nlpex.pyと打ってreturn

とコマンドを打つと、

*** Introductory Examples for the NLTK Book ***
Loading text1, ..., text9 and sent1, ..., sent9
Type the name of the text or sentence to view it.
Type: 'texts()' or 'sents()' to list the materials.
text1: Moby Dick by Herman Melville 1851
text2: Sense and Sensibility by Jane Austen 1811
text3: The Book of Genesis
text4: Inaugural Address Corpus
text5: Chat Corpus
text6: Monty Python and the Holy Grail
text7: Wall Street Journal
text8: Personals Corpus
text9: The Man Who Was Thursday by G . K . Chesterton 1908
Displaying 11 of 11 matches:
ong the former , one was of a most monstrous size . ... This came towards us , 
ON OF THE PSALMS . " Touching that monstrous bulk of the whale or ork we have r
ll over with a heathenish array of monstrous clubs and spears . Some were thick
d as you gazed , and wondered what monstrous cannibal and savage could ever hav
that has survived the flood ; most monstrous and most mountainous ! That Himmal
they might scout at Moby Dick as a monstrous fable , or still worse and more de
th of Radney .'" CHAPTER 55 Of the Monstrous Pictures of Whales . I shall ere l
ing Scenes . In connexion with the monstrous pictures of whales , I am strongly
ere to enter upon those still more monstrous stories of them which are to be fo
ght have been rummaged out of this monstrous cabinet there is no telling . But 
of Whale - Bones ; for Whales of a monstrous size are oftentimes cast up dead u
None

となります。

本の方ではsimilarやcommon_contextsなども紹介されていますが、コードの書き方自体では同じなので省略。(なるべく丁寧にという、自分なりの方針からはややそれますが、、、まぁいいか)


次は、分散プロットの表示です。
#先ほどの例と同様に、以下のように書いて例えばnlpex.pyとかいう名前で保存する。
import nltk
from nltk.book import *
text4.dispersion_plot(['citizens','democracy','freedom','duties','America'])


で、次のようにコマンドを打ちます。
hiroshi-no-MacBook-Air:Pro-tr hiroshi$ python3 nlpex.py


するとこういう画面が表示されます。

とりあえず、一旦ここで区切ります。

参考にしたページや文献・書籍
 『入門 入門自然言語処理』

2015年9月23日水曜日

Macでpython3の環境構築8---NLTKのインストール2---

前回の続きです。
(前回:Macでpython3の環境構築7---NLTKのインストール1---

nltk.download()とコマンドを打ってもうまくいかないというお話でした。

これは次のようなコマンドでも代替できるようです。

hiroshi-no-MacBook-Air:~ hiroshi$ python3 -m nltk.downloader book                
#  「python3 -m nltk.downloader book」と打ってreturnを押す。

そうすると、次のような処理が始まります。

[nltk_data] Downloading collection 'book'
[nltk_data]    |
[nltk_data]    | Downloading package abc to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package abc is already up-to-date!
[nltk_data]    | Downloading package brown to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package brown is already up-to-date!
[nltk_data]    | Downloading package chat80 to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package chat80 is already up-to-date!
[nltk_data]    | Downloading package cmudict to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package cmudict is already up-to-date!
[nltk_data]    | Downloading package conll2000 to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package conll2000 is already up-to-date!
[nltk_data]    | Downloading package conll2002 to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package conll2002 is already up-to-date!
[nltk_data]    | Downloading package dependency_treebank to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package dependency_treebank is already up-to-date!
[nltk_data]    | Downloading package genesis to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package genesis is already up-to-date!
[nltk_data]    | Downloading package gutenberg to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package gutenberg is already up-to-date!
[nltk_data]    | Downloading package ieer to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package ieer is already up-to-date!
[nltk_data]    | Downloading package inaugural to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package inaugural is already up-to-date!
[nltk_data]    | Downloading package movie_reviews to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package movie_reviews is already up-to-date!
[nltk_data]    | Downloading package nps_chat to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package nps_chat is already up-to-date!
[nltk_data]    | Downloading package names to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package names is already up-to-date!
[nltk_data]    | Downloading package ppattach to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package ppattach is already up-to-date!
[nltk_data]    | Downloading package reuters to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Package reuters is already up-to-date!
[nltk_data]    | Downloading package senseval to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/senseval.zip.
[nltk_data]    | Downloading package state_union to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/state_union.zip.
[nltk_data]    | Downloading package stopwords to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/stopwords.zip.
[nltk_data]    | Downloading package swadesh to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/swadesh.zip.
[nltk_data]    | Downloading package timit to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/timit.zip.
[nltk_data]    | Downloading package treebank to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/treebank.zip.
[nltk_data]    | Downloading package toolbox to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/toolbox.zip.
[nltk_data]    | Downloading package udhr to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/udhr.zip.
[nltk_data]    | Downloading package udhr2 to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/udhr2.zip.
[nltk_data]    | Downloading package unicode_samples to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/unicode_samples.zip.
[nltk_data]    | Downloading package webtext to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/webtext.zip.
[nltk_data]    | Downloading package wordnet to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/wordnet.zip.
[nltk_data]    | Downloading package wordnet_ic to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/wordnet_ic.zip.
[nltk_data]    | Downloading package words to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/words.zip.
[nltk_data]    | Downloading package maxent_treebank_pos_tagger to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping taggers/maxent_treebank_pos_tagger.zip.
[nltk_data]    | Downloading package maxent_ne_chunker to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping chunkers/maxent_ne_chunker.zip.
[nltk_data]    | Downloading package universal_tagset to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping taggers/universal_tagset.zip.
[nltk_data]    | Downloading package punkt to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping tokenizers/punkt.zip.
[nltk_data]    | Downloading package book_grammars to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping grammars/book_grammars.zip.
[nltk_data]    | Downloading package city_database to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping corpora/city_database.zip.
[nltk_data]    | Downloading package tagsets to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |   Unzipping help/tagsets.zip.
[nltk_data]    | Downloading package panlex_swadesh to
[nltk_data]    |     /Users/hiroshi/nltk_data...
[nltk_data]    |
[nltk_data]  Done downloading collection book
hiroshi-no-MacBook-Air:~ hiroshi$


では、次にそのまま、

hiroshi-no-MacBook-Air:~ hiroshi$ from nltk.book import *             
 #       $のあとにいきなり「from nltk.book import *」と打ってもうまくはいかない。

としても。。。

from: can't read /var/mail/nltk.book
hiroshi-no-MacBook-Air:~ hiroshi$

と返されうまくいきません。

今度はこうしてみます。

hiroshi-no-MacBook-Air:~ hiroshi$ python3

そうすると、こうなります。

Python 3.4.3 (default, Aug 11 2015, 08:57:25)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

また入力の待ち状態になるので、続けて二つコマンドを打ってみます。

>>> import nltk      #  「import nltk」と打ってreturnを押す。
>>> text1               #    続けてtext1と打ってreturnを押す。


それでも、やはりこうなってしまい失敗。

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'text1' is not defined
>>>

今度は、こうしてみます。
>>> from nltk.book import *         #  「from nltk.book import *」と打ってreturnを押す。

そうすると次のようになります。

*** Introductory Examples for the NLTK Book ***
Loading text1, ..., text9 and sent1, ..., sent9
Type the name of the text or sentence to view it.
Type: 'texts()' or 'sents()' to list the materials.
text1: Moby Dick by Herman Melville 1851
text2: Sense and Sensibility by Jane Austen 1811
text3: The Book of Genesis
text4: Inaugural Address Corpus
text5: Chat Corpus
text6: Monty Python and the Holy Grail
text7: Wall Street Journal
text8: Personals Corpus
text9: The Man Who Was Thursday by G . K . Chesterton 1908
>>>

最後に、「text1」と打って

>>> text1
<Text : Moby Dick by Herman Melvile 1851 >
>>>

となり、なんとか成功しました。

まとめとしては、「python3 -m nltk.downloader book」を行ったあとは
  1. python3  とコマンドを打つ。
  2. import nltk とコマンドを打つ。
  3. from nltk.book import * とコマンドを打つ。
  4. 最後にtext1と打って、上記のように表示されれば成功。
となります。

2015年9月22日火曜日

Macでpython3の環境構築7---NLTKのインストール1---

今回はNLTKをインストールしていきます。
まず、NLTK自体のインストールはすぐできます。
次のようにコマンドを打ちます。

hiroshi-no-MacBook-Air:~ hiroshi$ sudo pip3 install -u nltk          #       「sudo  pip3 install -u nltk」と打ってreturnを押す。

そうすると、パスワードを求められるので入力します。今までも出てきたので同じことの繰り返しになりますが、打っても入力できているようには見えませんが、きちんと認識はされています。

Password:          #  自分のPCのパスワードを入力。入力できているようには見えないけど、きちんと認識はされています。

そうすると以下のような処理がはしり、NLTKのインストールは終わりです。

The directory '/Users/hiroshi/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been
 disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
You are using pip version 7.1.0, however version 7.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
The directory '/Users/hiroshi/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache
 has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting nltk
  Downloading nltk-3.0.5.tar.gz (1.0MB)
    100% |████████████████████████████████| 1.0MB 325kB/s
Requirement already up-to-date: six>=1.9.0 in /usr/local/lib/python3.4/site-packages (from nltk)
Building wheels for collected packages: nltk
  Running setup.py bdist_wheel for nltk
  Stored in directory: /Users/hiroshi/Library/Caches/pip/wheels/f6/ef/3d/039e21095c9845e948931918734aa6c05df4d72f09
a3132c69
Successfully built nltk
Installing collected packages: nltk
Successfully installed nltk-3.0.5

hiroshi-no-MacBook-Air:~ hiroshi$ 


これで、NLTKのインストールは完了。
このあと、サンプルデータのインストールになりますが、これが少しやっかいかも。

続いて、次のようにコマンドを打ちます。
hiroshi-no-MacBook-Air:~ hiroshi$ python3        #「python3」と打ってreturnを押す。

そうすると次のようになり、また入力の待ち状態になります。

Python 3.4.3 (default, Aug 11 2015, 08:57:25)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>          #入力の待ち状態

そこにまたコマンドをうちます。

>>> import nltk       #「import nltk」と打ってreturnを押す。
>>> nltk.download()     #そうするとまた入力待ちになるので、続けて「nltk.download()」と打ってreturnを押す。

そうすると、
ターミナルの方は、
showing info http://www.nltk.org/nltk_data/

と表示されると同時に 新しい画面が立ち上がります。
で、上の画面はallが選ばれていますが、bookを選んで左下のDownloadを押します。
そうすると、/User/hiroshi/の中に、nltk_dataというフォルダが作成されます。
これでうまくいくはずなのですが、エラーが出てしまいました。

そのとき、ターミナル上は、こうなっています。

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.4.3_2/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tkinter/__init__.py", line 1533, in __call__
    return self.func(*args)
  File "/usr/local/lib/python3.4/site-packages/nltk/downloader.py", line 1569, in _download
    return self._download_threaded(*e)
  File "/usr/local/lib/python3.4/site-packages/nltk/downloader.py", line 1836, in _download_threaded
    assert self._download_msg_queue == []
AssertionError
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.4.3_2/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tkinter/__init__.py", line 1533, in __call__
    return self.func(*args)
  File "/usr/local/lib/python3.4/site-packages/nltk/downloader.py", line 1569, in _download
    return self._download_threaded(*e)
  File "/usr/local/lib/python3.4/site-packages/nltk/downloader.py", line 1836, in _download_threaded
    assert self._download_msg_queue == []
AssertionError

このinvalid argumentというのをそのまま検索してみると、引数が不正、無効、とのこと。
一体なんのことやら。。。
わかる方がいたら教えてください。

よくわからないので、新しく出た画面の方はバツとじをしてしまいました。
そうすると、Trueとターミナル上には表示されます。

#####先ほどの続きから。中略。########
  File "/usr/local/lib/python3.4/site-packages/nltk/downloader.py", line 1569, in _download
    return self._download_threaded(*e)
  File "/usr/local/lib/python3.4/site-packages/nltk/downloader.py", line 1836, in _download_threaded
    assert self._download_msg_queue == []
AssertionError
True        #バツとじをするTrueと表示される。

全然うまくいっている感じはしないけれど、(そもそもエラーでたし)念のためうまくいっているかどうか確認をすることに。
「from nltk.book import *」と打って、「text1」と打って、「<Text: Moby Dick by Herman Melville 1851>」と表示されればうまくいったかどうかの確認らしい。

先ほどのところでTrueとでたあとはまた入力待ちのような状態になっているので、次ようにまた打ち込みます。
>>> from nltk.book import *       #    「from nltk.book import *」と打ってreturnを押す。

そうするとつぎのようになります。
*** Introductory Examples for the NLTK Book ***
Loading text1, ..., text9 and sent1, ..., sent9
Type the name of the text or sentence to view it.
Type: 'texts()' or 'sents()' to list the materials.
text1: Moby Dick by Herman Melville 1851
text2: Sense and Sensibility by Jane Austen 1811
text3: The Book of Genesis
text4: Inaugural Address Corpus
text5: Chat Corpus
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/site-packages/nltk/corpus/util.py", line 63, in __load
    try: root = nltk.data.find('corpora/%s' % zip_name)
  File "/usr/local/lib/python3.4/site-packages/nltk/data.py", line 624, in find
    raise LookupError(resource_not_found)
LookupError:
**********************************************************************
  Resource 'corpora/webtext.zip/webtext/' not found.  Please use
  the NLTK Downloader to obtain the resource:  >>> nltk.download()
  Searched in:
    - '/Users/hiroshi/nltk_data'
    - '/usr/share/nltk_data'
    - '/usr/local/share/nltk_data'
    - '/usr/lib/nltk_data'
    - '/usr/local/lib/nltk_data'
**********************************************************************

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python3.4/site-packages/nltk/book.py", line 34, in 
    text6 = Text(webtext.words('grail.txt'), name="Monty Python and the Holy Grail")
  File "/usr/local/lib/python3.4/site-packages/nltk/corpus/util.py", line 99, in __getattr__
    self.__load()
  File "/usr/local/lib/python3.4/site-packages/nltk/corpus/util.py", line 64, in __load
    except LookupError: raise e
  File "/usr/local/lib/python3.4/site-packages/nltk/corpus/util.py", line 61, in __load
    root = nltk.data.find('corpora/%s' % self.__name)
  File "/usr/local/lib/python3.4/site-packages/nltk/data.py", line 624, in find
    raise LookupError(resource_not_found)
LookupError:
**********************************************************************
  Resource 'corpora/webtext' not found.  Please use the NLTK
  Downloader to obtain the resource:  >>> nltk.download()
  Searched in:
    - '/Users/hiroshi/nltk_data'
    - '/usr/share/nltk_data'
    - '/usr/local/share/nltk_data'
    - '/usr/lib/nltk_data'
    - '/usr/local/lib/nltk_data'
**********************************************************************
>>>


やはりうまくいっている感じは全然しないけれど、続けます。
>>> text8     #「text8」と打ってreturnを押す。

が、やはり
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'text8' is not defined

となってしまいます。「NameError: name 'text8' is not defined」とか言われてるしね。。。
text5とかtext1とかでやっても同じです。

しらべてみると、「nltk.download()」のくだりは別の方法でもできるらしい。
結局今回のエラーについて原因はよくわからないままでしたが、あとまわしにして別の方法で、試してみたいと思います。それは次回。