2009年3月8日日曜日

文体とリズムの視覚化 Part2

 前回は、目的と全体の概要などを述べた。
 
 ※ コード部分読みにくい色になってます。後で修正します。 修正しました。

 今回は、文章を入力してそれを構成要素に分ける部分の実装を行う。手順は以下のようになる。

1.  入力文字列を設定する.
2.  Yahooデベロッパーの日本語形態素解析に、要素に分けてもらう.
3.  結果を保持する.

 保持したものは今後の視覚化に使う、ということになる。

 上記の機能を持つクラスをRubyで実装する。
 単語の品詞、表記、読みを1つの単位として、入力された単語数分が結果として得られる。単語の扱いを簡単にするために、単語を扱うWordクラスを作った。こんな感じ。
#!/usr/bin/ruby -Ku

class Word

attr_accessor :surface #表記
attr_accessor :pos #品詞
attr_accessor :reading #読み

end

 実際に、YahooデベロッパーのAPIを呼び出すのは以下のMorphemeクラス。入力する文字列を設定できて、YahooデベロッパーのAPIを呼び出すことができる。結果は、上のWordクラスの配列に保持する、という単純な感じ。
#!/usr/bin/ruby -Ku

require 'open-uri'
require 'rexml/document'
require 'word.rb'

class Morpheme

attr_accessor :sentence, :words

def initialize(sentence = nil)
@appid = 'YourID'
@xmluri = 'http://api.jlp.yahoo.co.jp/MAService/V1/parse'
@results = 'ma'

@sentence = sentence
end

def morpheme
@words = Array.new

body = open("#{@xmluri}?appid=#{@appid}&results=#{@results}&sentence=" + URI.encode("#{@sentence}"))

doc = REXML::Document.new(body).elements['ResultSet/ma_result/word_list']
doc.elements.each('word') do |item|

word = Word.new

word.pos = item.elements["pos"].text
word.surface = item.elements["surface"].text
word.reading = item.elements["reading"].text

@words << word
end
end
end

 これで、Yahooデベロッパーを使って、形態素解析をしてくれる処理はとりあえず揃ったかな。

0 件のコメント: