院生エンジニアのにっき

  • Change style to Blue
  • Change style to Red
  • Change style to Green
  • Change style to Pink

PHPで直接MeCabの結果を利用する   2008-11-12

Page2にてMecab Extentionなるものも存在するんですが、こちらなどを参考にしてmorph_analysis関数を作ってみました。

やってる内容は至極簡単。

MeCabプロセスに対して文字列を投げて返ってきた値をパースしているだけ。

  1. define('Mecab_Encoding', 'SJIS');
  2. define('Mecab_ResultEncoding', 'UTF-8');
  3. define('MeCab_Path', 'mecab.exe');
  4. function morph_analysis($text) {
  5.   $text = mb_convert_encoding($text, Mecab_Encoding, Mecab_ResultEncoding);
  6.   $descriptorspec = array (
  7.     0 => array ("pipe",   "r"), // stdin
  8.     1 => array ("pipe", "w") // stdout
  9.   );
  10.   $process = proc_open(MeCab_Path, $descriptorspec, $pipes);
  11.   if (is_resource($process)) {
  12.     // mecabに文章を与える
  13.     fwrite($pipes[0], $text);
  14.     fclose($pipes[0]);
  15.     // 結果を読み取る
  16.     while (!feof($pipes[1])) {
  17.       $result .= fread($pipes[1], 4096);
  18.     }
  19.     fclose($pipes[1]);
  20.     proc_close($process);
  21.    
  22.     $result = mb_convert_encoding($result, Mecab_ResultEncoding, Mecab_Encoding);
  23.     $lines = explode("\r\n", $result);
  24.     $res = array();
  25.     foreach($lines as $line) {
  26.       if(in_array(trim($line), array('EOS', ''))) {continue;}
  27.       $s = explode("\t", $line);
  28.       $word = $s[0];
  29.       $words = explode(',', $s[1]);
  30.       //基本形などを利用したい場合はここに追加
  31.       $res[] = array(
  32.         'word' => $word,
  33.         'class' => $words[0],
  34.         'detail1' => $words[1],
  35.         'detail2' => $words[2],
  36.         'detail3' => $words[3],
  37.         'conjugation1' => $words[4],
  38.         'conjugation2' => $words[5]
  39.       );
  40.     }
  41.     return $res;
  42.   } else {
  43.     return false;
  44.   }
  45. }

MeCabを使ってブログの形態素解析をしているんですが、やはり精度はかなり悪いですね。ブログには顔文字もあるし、誤字・脱字も多い&口語表現・・・・なにかいい方法はないか模索中。。


コメントを書く