exp777.hatenablog.com

頭の中はゲームでいっぱい

RubyでMeCabを呼び出す

シンプルだけどけっこう使いやすいものができたと思う。

#!/bin/ruby -Ks

require 'kconv'

class MeCab

  MECAB_PATH = '"c:/program files/mecab/bin/mecab.exe"' # MeCabへのパス
  EOS = "EOS\n"
  
  @encode = ""
  @option = ""
  
  def initialize(encode, option = "")
    @encode = encode
    @option = option
    cmd_string = [MECAB_PATH, option].join(" ")
    @io = IO.popen(cmd_string, "r+")
  end

  def parse(str)
    result = ""
    @io.puts(Kconv.kconv(str, @encode))
    @io.each_line do |line|
      break if(line == EOS)
      result += line + "\n"
    end
    return result
  end
  
end

本体へのパスはコンストラクタで指定した方が良いかもね。