Yahoo!Japanのテキスト形態素解析Webサービス
ある単語をGoogle検索し、検出頻度から関連語を抽出するというものです。本当に関係しているかは無根拠。形態素解析器としてChasen、Mecab等を導入するのは億劫だったのでYahoo!のテキスト解析サービスを利用させてもらってます。一日50000件は多すぎず、少なすぎずといった感じですね。
# relative_word.rb # require 'rubygems' require 'hpricot' require 'open-uri' require 'rexml/document' require 'kconv' Appid = 'Yahoo!から割り当てられたアプリケーションID' Uri = 'http://api.jlp.yahoo.co.jp/MAService/V1/parse' Google_API = "http://www.google.co.jp/search?num=20&lr=lang_ja&oe=utf-8&q=" # 日本語で20件検索 def analyse_text(uri) result = Hpricot( open(uri).read ) analysed_xml = Array.new (result/:a).remove # 関連やページといった単語が引っかかるので、aタグは消去 (result/"span.a").remove # ドメインとか載っているところも余計 (result/"div.std").each {|text| analysed_xml << REXML::Document.new( open("#{Uri}?appid=#{Appid}&result=ma&sentence="+URI.encode(text.inner_text.toutf8)) ) } noun_array = Array.new analysed_xml.each {|xml| xml.elements['/ResultSet/ma_result/word_list/'].each {|word| noun_array << word.elements['surface'].text if word.elements['pos'].text.tosjis == "名詞".tosjis } } noun_array end search_word = ARGV.shift uri = Google_API + URI.encode(search_word) h = Hash.new(0) # 単語の検出回数を調べる analyse_text(uri).each do |noun| h[noun] += 1 end # 5個以上検出したら表示(個数は無根拠)、検索語は検出しない h.each do |noun, value| print noun.tosjis, " => ", value, "\n" if value > 5 && noun.tosjis != search_word .tosjis end
ruby relative_word.rb
放送 => 6
アニメ => 7
ルルーシュ => 15
2 => 7
反逆 => 15
Googleで検索、Yahoo!で解析という流れなので遅い遅い(あくまでRubyのせいにはしない)。つうかこれ本当に効果あるのかな?でも、コードギアスで調べて、アニメやルルーシュといった単語が出るのは嬉しいな。