LoginSignup
31
30

More than 5 years have passed since last update.

macでmecab-rubyをビルドせずにインストールする

Last updated at Posted at 2013-09-04

背景

rubyからMeCabを利用しようとすると、
ソースを取得し、makeしてinstallしなければならないし、
場合によってはMakefileの修正も必要なのであまり好きではありませんでした。

しかしふとgem search mecabしてみると

*** REMOTE GEMS ***

mecab (0.98)
mecab-ext (1.0.2)
mecab-light (0.2.2)
mecab-modern (0.0.2)
mecab-mora (0.0.5)
mecab-syllable (0.0.5)

なんとgemからインストールできそうではありませんか。

インストールを試みる

brewでmecabをインストールして

brew install mecab mecab-ipadic

bundle init
してGemfile
gem 'mecab'を追加し、
bundle installしてみると・・・

盛大なエラーが・・・

brewでインストールしたmecabのバージョンが0.996で、
gemのmecab-rubyのバージョンが0.98であることが原因です。

brewでバージョンを指定してインストール

brewでmecabをバージョン指定してみます。

まず、mecabが登録されているバージョンを調べてみます。

brew versions mecab

0.98はちゃんと存在しました。

0.996    git checkout ee21df2 /usr/local/Library/Formula/mecab.rb
0.995    git checkout 1c6ad82 /usr/local/Library/Formula/mecab.rb
0.994    git checkout 4844910 /usr/local/Library/Formula/mecab.rb
0.993    git checkout 642c664 /usr/local/Library/Formula/mecab.rb
0.992    git checkout bb95f13 /usr/local/Library/Formula/mecab.rb
0.99     git checkout 01788c0 /usr/local/Library/Formula/mecab.rb
0.98     git checkout 0476235 /usr/local/Library/Formula/mecab.rb

このバージョン0.98を利用するには/usr/localに移動して、指定のバージョンをチェックアウトします。

git checkout 0476235 /usr/local/Library/Formula/mecab.rb

改めてbrew install mecabしてインストールしてみましょう。

==> Downloading http://downloads.sourceforge.net/project/mecab/mecab/0.98/mecab-0.98.tar.gz

curl: (22) The requested URL returned error: 404
Error: Download failed: http://downloads.sourceforge.net/project/mecab/mecab/0.98/mecab-0.98.tar.gz

だめだ、リンク死んでる・・・

回避するためにbrew edit mecabしてbrewのformulaファイルを書き換えます。

require 'formula'

class Mecab < Formula
  # url 'http://downloads.sourceforge.net/project/mecab/mecab/0.98/mecab-0.98.tar.gz'
  url 'https://mecab.googlecode.com/files/mecab-0.98.tar.gz'
  homepage 'http://mecab.sourceforge.net/'
  # md5 'b3d8d79e35acf0ca178e8d885309f5fd'
  sha1 '8977d7760638ec65132e1f9bfc66655ac761f964'

  def install
    system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}"
    system "make install"
  end
end

いったんbrew uninstall mecab mecab-ipadicして、
改めてbrew install mecab mecab-ipadicすると無事mecab 0.98が使えるようになり、
bundle installでmecab-rubyもビルド出来ました。

rubyからmecabを使うテスト

簡単なサンプルコードを動かしてみます。

require "mecab"

node = MeCab::Tagger.new.parseToNode("本日は晴天なり")
while node
  puts "#{node.surface}\t#{node.feature}"
  node = node.next
end

実行結果

   BOS/EOS,*,*,*,*,*,*,*,*
本日 名詞,副詞可能,*,*,*,*,本日,ホンジツ,ホンジツ
は  助詞,係助詞,*,*,*,*,は,ハ,ワ
晴天 名詞,一般,*,*,*,*,晴天,セイテン,セイテン
なり 助動詞,*,*,*,文語・ナリ,基本形,なり,ナリ,ナリ
   BOS/EOS,*,*,*,*,*,*,*,*

動作しました。

バージョンの一致には気をつける必要がありますが、
bundle管理でgemからインストールできるようになっただけでも便利になりました。

31
30
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
30