🐘 『入門 自然言語処理』メモ (4) - Textクラス
作成日: 2021/11/12
0

『入門 自然言語処理』の第1章には nltk.book からテキストをインポートして操作する例が示してあります。このとき使われるメソッドの多く(collocations(), concordance() など)は Textクラスという NLTKに特有なクラスに属しています。

>>> type(text1)  
<class 'nltk.text.Text'>

独自に作ったコーパスのテキストファイルにこれらのメソッドを適用するとエラーになります。

>>> feino_words.collocations()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'StreamBackedCorpusView' object has no attribute 'collocations'

独自のテキストファイルに Textクラスを付与するには、nltk.Text() という関数を使います。

>>> type(feino_words)
<class 'nltk.corpus.reader.util.StreamBackedCorpusView'>
>>> feino_text = nltk.Text(feino_words)
>>> type(feino_text)
<class 'nltk.text.Text'>

これで collocations() や concordance() メソッドが使えるようになります。

>>> feino_text.collocations()
malfeliĉa infano; ŝia buŝo; arĝentan vazon; granda estos; kiel granda;
estas tiel; prenis sur; sur sin; ĉerpi akvon; perloj kaj; sia patro;
ĉiu vorto; por vidi; tiu sama; malriĉa virino; pli juna; por doni; via
buŝo; ŝia patrino; mia filino
>>> feino_text.concordance('bela')  
Displaying 4 of 4 matches:
 Tre volonte , mia bona ,”; diris la bela knabino . Kaj ŝi tuj lavis sian kruĉ
iris al la knabino : “ Vi estas tiel bela , tiel bona kaj tiel honesta , ke mi
o aŭ multekosta ŝtono .” Kiam tiu ĉi bela knabino venis domen , ŝia patrino in
s ; kaj , vidante , ke ŝi estas tiel bela , li demandis ŝin , kion ŝi faras ti

ただし、concordance() で 'bela' を検索する場合 'belaj' や 'belan'、'belajn' のような変化形は含まれないので、別に処理する必要があります。


pythonで自然言語処理プログラムが書けるようになりたいと思っています。Ticketnoteで自分の到達度を確認できれば嬉しいです。