NLTKを使ってみる---『入門 自然言語処理』を読む1----
ずいぶんと前になりますが、
と
で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
するとこういう画面が表示されます。
とりあえず、一旦ここで区切ります。
- 作者: Steven Bird,Ewan Klein,Edward Loper,萩原正人,中山敬広,水野貴明
- 出版社/メーカー: オライリージャパン
- 発売日: 2010/11/11
- メディア: 大型本
- 購入: 20人 クリック: 639回
- この商品を含むブログ (44件) を見る