無料で使えるシステムトレードフレームワーク「Jiji」 をリリースしました!

・OANDA Trade APIを利用した、オープンソースのシステムトレードフレームワークです。
・自分だけの取引アルゴリズムで、誰でも、いますぐ、かんたんに、自動取引を開始できます。

形態素解析を行うサンプル

Yahoo! Developer APIの形態素解析サービスを利用して、テキストの形態素解析を行うサンプルです。昨日の特徴語抽出クラスに機能を追加する感じで作成。

  • 例によって
    • 依存モジュールとして「httpclient」が必要です。
    • また、実行時には、Yahoo! Developer APIのアプリケーションIDも必要になります。
  • あと、昨日の実装ではYahoo!のサイトの呼び出し例に流されてGETでリクエストを投げていましたが、テキストが長くなった場合にこれじゃダメだよね、ということでPOSTを使うように修正しています。
require 'rubygems'
require 'httpclient'
require 'rexml/document'

module YahooDeveloperAPI
  
  HOST_JLP = "http://jlp.yahooapis.jp"
  
  class Client
    def initialize( appid, proxy=ENV["http_proxy"] )
      @appid = appid
      @client = HTTPClient.new( proxy, "client")
    end
    
    #テキストから特徴語を抽出する。
    #text:: テキスト
    #戻り値:: 特徴語の配列
    def extract_keyphrase( text )
      result = @client.post( "#{HOST_JLP}/KeyphraseService/V1/extract", 
          "appid=#{@appid}&#{gen_param( {:sentence=>text} )}" )
      doc = REXML::Document.new(result.content)
      return read_result_set( doc, "/ResultSet/Result" )
    end
    
    #テキストの形態素解析を行う
    #text:: テキスト
    #option:: 追加の設定(http://developer.yahoo.co.jp/webapi/jlp/ma/v1/parse.htmlのパラメータの項を参照)
    #戻り値:: 解析結果
    def parse( text, option={} )
      option[:sentence] = text
      result = @client.post( "#{HOST_JLP}/MAService/V1/parse", 
          "appid=#{@appid}&#{gen_param( option )}" )
      doc = REXML::Document.new(result.content)
      return {
        :ma_result=>{
          :total_count=>doc.text("/ResultSet/ma_result/total_count").to_i,
          :filtered_count=>doc.text("/ResultSet/ma_result/filtered_count").to_i,
          :words=>read_result_set( doc, "/ResultSet/ma_result/word_list/word" )
        }, 
        :uniq_result=>{
          :total_count=>doc.text("/ResultSet/uniq_result/total_count").to_i,
          :filtered_count=>doc.text("/ResultSet/uniq_result/filtered_count").to_i,
          :words=>read_result_set( doc, "/ResultSet/uniq_result/word_list/word" )
        }
      }
    end
    
  private
    #URLパラメータを生成する
    def gen_param(param)
      param.map{|k| "#{k[0]}=#{URI.encode(k[1].to_s)}" }.join("&")
    end
    #ResultSetをデータの配列に変換する
    def read_result_set(doc, path)
      list = []
      doc.elements.each(path) {|e|
        tmp = {}
        e.elements.each("*") {|child|
          tmp[child.name.to_sym] = child.text
        }
        list << tmp
      }
      return list
    end
  end
end

# サンプル
client = YahooDeveloperAPI::Client.new( "<アプリケーションID>" )
text =  IO.read("./src.txt")
result = client.parse(text,{:results=>"ma,uniq", :filter=>"9"})
puts "---形態素解析結果"
result[:ma_result][:words].each {|w|
  puts "#{w[:surface]} : #{w[:pos]}"
}
puts "---出現頻度"
result[:uniq_result][:words].each {|w|
  puts "#{w[:surface]} : #{w[:count]}"
}

実行結果です。

---形態素解析結果
今日 : 名詞
ワイン : 名詞
カベルネ : 名詞
フラン : 名詞
メルロー : 名詞
ワイン : 名詞
... 略

---出現頻度
ボジョレー : 6
ワイン : 6
帰宅 : 5
とき : 4
インフル : 4
パスタ : 4
... 略