JUMAN/KNPのruby用ラッパー

最近こんなことばっかしてるけどとりあえずJUMAN/KNPのrubyラッパーの雛型ができたので晒す。

jumanknp.rb

#! ruby -Ke

require 'socket'

class JumanKnpParser
  def initialize(name)
    @name = name
    @juman_s = nil
    @knp_s = nil
  end
  
  def juman_socket(name,port,option)
    until @juman_s
      begin 
        @juman_s = TCPSocket.open(name,port)
      rescue
        STDERR.print "JUMANとの接続に失敗しました。再接続しています。\n"
        sleep 5
        
        retry
      end
    end
    STDERR.print "JUMANに接続しました\n"
    input_a = ["RUN\s",option,"\n"]
    input = input_a.join('')
    @juman_s.write(input)
    STDERR.print @juman_s.gets
    STDERR.print @juman_s.gets
    STDERR.print "JUMAN running on \"#{option}\" MODE............\n"
    return
  end
  
  def knp_socket(name,port,option)
     until @knp_s
      begin 
        @knp_s = TCPSocket.open(name,port)
      rescue
        STDERR.print "KNPとの接続に失敗しました。再接続しています。\n"
        sleep 5
        
        retry
      end
    end
    
    STDERR.print "KNPに接続しました\n"
    input_a = ["RUN\s",option,"\n"]
    input = input_a.join('')
    @knp_s.write(input)
    STDERR.print @knp_s.gets
    STDERR.print @knp_s.gets
    STDERR.print "KNP running on \"#{option}\" MODE............\n"
    return
  end

  def juman_parse(input)
    juman_result_a = Array.new
    @juman_s.write(input)
    while true
      f = @juman_s.gets
      juman_result_a.push(f)
      break if f.to_s == "EOS\n"
    end
    return juman_result_a
  end

  def knp_parse(input)
    knp_result_a = Array.new
    input.each do |juman_result|
      @knp_s.write(juman_result)
    end
    while true
      f = @knp_s.gets
      knp_result_a.push(f)
      break if f.to_s =~ (/EOS/e)
    end
    return knp_result_a
  end

  def juman_close
    @juman_s.close
  end

  def knp_close
    @knp_s.close
  end

end

つかいかた。
1.↑をカレントディレクトリかRUBYLIBのpathが通ってるとこにおく。
2.JUMANとKNPのサーバモードを立ち上げる。

juman -S
knp -S

これでlocalhostの32000と31000でJUMANとKNPが待機する。
3.あとはこんな感じ。

test.rb

#! ruby -Ke

require 'socket'
require 'jumanknp'

jumanknp_s = JumanKnpParser.new('test')

#JUMAN/KNPのポートとオプションを指定する
jumanknp_s.juman_socket("localhost",32000,'-e2')
jumanknp_s.knp_socket("localhost",31000,'-tab')

while text = gets
  
  jumanresult = jumanknp_s.juman_parse(text)
  knpresult = jumanknp_s.knp_parse(jumanresult)
  print knpresult

end

jumanknp_s.juman_close
jumanknp_s.knp_close