x**3な人生

基本的にはメモ

NLTKのWordnetを使ってみる 2

久々の更新。しばらく使わないうちにversion upして、少し変わったところもあるようなのであらためておさらいをする。
(ちなみに当方MacOSX)

(0)環境構築
http://www.nltk.org/Homeから一式をダウンロード、インストール。

(1)モジュールをインポートする。

>>> from nltk.wordnet import *

とすると、

Resource 'corpora/wordnet/index.noun' not found.  Please use the
  NLTK Downloader to obtain the resource: >>> nltk.download().

と表示される。
nltk.download()しないといけないのか、と思いつつ素直に入力すると、GUIの管理ツールが起ち上がるので、全てインストールする。
今度は正常にモジュールをインポートすることができる。

(2)名詞、動詞、形容詞など ('Word' object)
前回と同じように

>>> noun = N['dog']     # 名詞
>>> verb = V['run']     # 動詞
>>> adjective = ADJ['large'] # 形容詞
>>> adverb = ADV['largely']  # 副詞

としてみたところ、

Function __init__() has been deprecated.  Use
  nltk.corpus.wordnet.Lemma() instead.

のような警告が出力される。
気にしないことにする。

>>> noun.form
'dog'
>>> noun.pos
'noun'

(3)'Synset' object

# synsetを見てみる
>>> N['dog'].synsets()
[{noun: dog, domestic_dog, Canis_familiaris}, {noun: frump, dog}, {noun: dog}, {noun: cad, bounder, blackguard, dog, hound, heel}, {noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, weenie}, {noun: pawl, detent, click, dog}, {noun: andiron, firedog, dog, dog-iron}]

# synsetの中身にアクセスしてみる
>>> dog_syns = N['dog'].synsets()
>>> dog_syns[0]
{noun: dog, domestic_dog, Canis_familiaris}
>>> dog_syns[0][0]
dog
>>> dog_syns[0][1]
domestic_dog

# hypernym(上位語)
>>> dog_syns[0][HYPERNYM]
[{noun: canine, canid}, {noun: domestic_animal, domesticated_animal}]

# インスタンス変数
# 1. gloss
>>> dog_syns[0].gloss
'a member of the genus Canis (probably descended from the common wolf) that has been domesticated by man since prehistoric times; occurs in many breeds; "the dog barked all night"'
# 2. offset
>>> dog_syns[0].offset
2084071
# 3. pos
>>> dog_syns[0].pos   
'noun'
# 4. verbFrames
#    verbなので動詞のsynsetsを新たに生成する
>>> think_syns = V['think']
>>> think_syns[0]
{verb: think, believe, consider, conceive}
>>> think_syns[0].verbFrames
(5, 9)

# treeで遡って見てみる
>>> from pprint import pprint # 階層構造を見やすく表示するためにpprintを使う
>>> pprint(dog_syns[0].tree(HYPERNYM))
[{noun: dog, domestic_dog, Canis_familiaris},
 [{noun: canine, canid},
  [{noun: carnivore},
   [{noun: placental, placental_mammal, eutherian, eutherian_mammal},
    [{noun: mammal, mammalian},
     [{noun: vertebrate, craniate},
      [{noun: chordate},
       [{noun: animal, animate_being, beast, brute, creature, fauna},
        [{noun: organism, being},
         [{noun: living_thing, animate_thing},
          [{noun: whole, unit},
           [{noun: object, physical_object},
            [{noun: physical_entity}, [{noun: entity}]]]]]]]]]]]]],
 [{noun: domestic_animal, domesticated_animal},
  [{noun: animal, animate_being, beast, brute, creature, fauna},
   [{noun: organism, being},
    [{noun: living_thing, animate_thing},
     [{noun: whole, unit},
      [{noun: object, physical_object},
       [{noun: physical_entity}, [{noun: entity}]]]]]]]]]

今日はここまで