Less is Best

rubyが好き。技術の話とスタートアップに興味があります。

入門自然言語処理1章を読みはじめるので。

入門 機械学習

入門 機械学習

章末の練習問題を解いたログをぽいっと。

Pythonなどをはじめちゃっておりますが、ちょっと作りたいものが出来たので、そのためにこんな本を読み始めました。 とりあえず、1章まで読み終えたのでその練習問題の解答を上げてみます。 簡単なのは飛ばして、とりあえず勉強になりそうなものをやりました。

引っかかりそうなとこまとめ

①問28: pythonにて直感的に正確な計算をしたい場合(小数の割り算)from __future__ import divisionを書いておく。 ②問24,25:for文の中でifを使う使い方(なぜか1度引っかかったので)

17."sunset"という単語の1文をtext9の中から抜き出せ

#coding: utf-8

#text9.index('sunset')
import nltk
from nltk.book import *

pre_dot = 0 #直前のdot
aft_dot = 0  #直後のdot
found = False #"."が発見されたかどうか
i = 0 #index

for w in text9:
  if w == "sunset":
    found = True
  if w == ".": 
    if found == True:
      aft_dot = i
      break
    else:
      pre_dot = i
  i += 1
    
#sunsetを含む最初の一文を生成
print " ".join(text9[pre_dot+1:aft_dot+1])

18. sent1からsent8までに含まれる語彙を計算

ここをみて2つの文字列を変数として扱う方法でやってみる。

#coding: utf-8

import nltk
from nltk.book import *

sentences = []
for i in range(1,9):
  sentences += eval("sent"+ str(i))

print len(set(sentences))

19. 以下2行の違いは何か。

sorted(set([w.lower() for w in text1])) #a
sorted([w.lower() for w in set(text1)]) #b

aは小文字にしてからユニークに bはユニークにしてから小文字にしているので、 bの方が重複を含んでいる。

20.w.isupper()not w.islower()の違いは何か

  1. w.isupper()は全て大文字 not w.islower()は全て小文字というわけではない

    21.text2のさいごの2単語を取り出すスライス式

    text2[-2:]

23.text6の大文字だけで構成された単語を1行に出力せよ

#coding: utf-8

import nltk
from nltk.book import *

for w in text6:
  if w.isupper():
    print w,

24.text6で以下の条件に合致するリストを出力せよ

a: izeで終わる b: zを含む c: ptを含む d: 先頭大文字あと小文字(=タイトルケース) ちょっと不満。forで回してif文で条件分岐できるはず…だよね? どうしてできないの…orz

import nltk
from nltk.book import *

print[t for t in text6 if t.endswith('ize')]
print[t for t in text6 if 'z' in t]
print[t for t in text6 if 'pt' in t]
print[t for t in text6 if t.isalpha()==True and t==t.title()]

25.['she', 'sells', 'sea', 'shells', 'by', 'the', 'sea', 'shore']に大して以下の処理をしろ

a.「sh」で始まる全ての単語を出力 b.4文字よりも長い単語を全て出力

とおもったらググったらでてきた。 24も同じようにやればできますね。笑

words = "she sells sea shells by the sea shore".split(' ')

ans1 = []
for w in words:
  if w.startswith('sh'):
    ans1.append(w)
print ans1

ans2 = []
for w in words:
  if len(w) > 4:
    ans2.append(w)
print ans2

27.テキストのみを引数にとり、テキストの語彙サイズを返すvocab_size(text)関数の定義をしろ

#coding: utf-8

#text9.index('sunset')
import nltk
from nltk.book import *

def vocab_size(text):
  return len(set(text))

28.percent(word,text)関数の定義

pythonにて直感的に正確な計算をしたい場合(小数の割り算)from __future__ import divisionを書いておく。

#coding: utf-8
from __future__ import division
import nltk
from nltk.book import *


def percent(word,text):
  fdist = FreqDist(text)
  return fdist[word] / len(text) * 100

print percent('the',text1)