hiroshi akutsuの日記

主にプログラミング関係のこと

perl【CentOS6でText::MeCabを使う】

いつもcpanからText::MeCabのインストールでエラーが出て苦しんでいるので、備忘録としてまとめます。

まず環境

CentOS 6.7
Perl 5.10.1

作業ディレクトリはどこでもいいです。
まずmecabのインストール

wget http://mecab.googlecode.com/files/mecab-0.996.tar.gz
tar xvzf mecab-0.996.tar.gz
cd mecab-0.996
./configure
make
make check
sudo make install

mecab辞書のインストール

wget http://mecab.googlecode.com/files/mecab-ipadic-2.7.0-20070801.tar.gz
tar xvzf mecab-ipadic-2.7.0-20070801.tar.gz
cd mecab-ipadic-2.7.0-20070801
./configure --with-charset=utf8
make
sudo make install


PerlCentOSをインストールした際にデフォルトで入ってくるバージョンが5.10.1だったのですが、この古いバージョンではText::MeCabはインストールできないのでバージョンを上げます。

いくつか方法はあると思いますが、perlbrewというのが簡単そうだったので、これを使います。


[https://www.seeds-std.co.jp/seedsblog/611.html:title]

ユーザーごとにperlの実行環境を切り替えられるのは便利です。

インストール

curl -kL http://install.perlbrew.pl | bash

perlbrewのpathを通す

echo "source ~/perl5/perlbrew/etc/bashrc" >> ~/.bashrc
source ~/perl5/perlbrew/etc/bashrc

利用可能なバージョン一覧

perlbrew available

5.16.3をインストール

perlbrew install 5.16.3

5.16.3に切り替え

perlbrew switch 5.16.3

バージョンおよびパス確認

$ perl -v

This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux
(with 1 registered patch, see perl -V for more detail)

Copyright 1987-2012, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.

$ which perl
~/perl5/perlbrew/perls/perl-5.16.3/bin/perl


次にcpanからText::MeCabをインストールしますが、その前にmecabのライブラリへのパスを
/etc/ld.so.conf.d/
に追記し、Text::MeCabをインストールします。

$ sudo su
# echo "/usr/local/lib" >> /etc/ld.so.conf.d/local.conf
# ldconfig
# exit
$ cpan install Text::MeCab


インストールの途中
Encoding of your mecab dictionary? (shift_jis, euc-jp, utf-8) [euc-jp]
と聞かれるので、utf-8を指定します。



これで入ると思います。

テストを実行してみます。

text.plをどこかに作成

#! /home/akutsu/perl5/perlbrew/perls/perl-5.16.3/bin/perl

use strict;
use warnings;
use Text::MeCab;

my $m = Text::MeCab->new();
my $s = "すもももももももものうち。";
my $n = $m->parse($s);
my $t = "";
while ($t = $n->next){

	printf("%s\t%s\t%d\n",
		$n->surface,
		$n->feature,
		$n->cost
	);
	$n = $t;
}
$ perl text.pl
すもも	名詞,一般,*,*,*,*,すもも,スモモ,スモモ	7263
も	助詞,係助詞,*,*,*,*,も,モ,モ	7774
もも	名詞,一般,*,*,*,*,もも,モモ,モモ	15010
も	助詞,係助詞,*,*,*,*,も,モ,モ	15521
もも	名詞,一般,*,*,*,*,もも,モモ,モモ	22757
の	助詞,連体化,*,*,*,*,の,ノ,ノ	23131
うち	名詞,非自立,副詞可能,*,*,*,うち,ウチ,ウチ	23729
。	記号,句点,*,*,*,*,。,。,。	22725