Windows+PHPでmecabを実行するときの方法例。詳しくは
外部コマンドの実行や
proc_open()を読んでいただきたい。
ちなみにmecabには--eos-format=でEOSの代わりの文字を指定でき、mecab --eos-format=endとすると終わりがendになる。
また、mecabは基本1文を解析するのにつかわれるため複数行の解析には適していないようだ。出力バッファの関係から入力バッファの
サイズは512に指定してあるらしい。
//Mecabの置いてある所。環境によって要変更。""で囲ってあるのはProgram Filesの間の空白を認識しないため。
$mecabpath = '"C:\\Program Files\\MeCab\\bin\\mecab.exe\\"';
$inputfile = "すもももももももものうち"
$descriptorspec = array(
0 => array("pipe","r"), //stdin
1 => array("pipe","w") //stdout
);
$inputfile = mb_convert_encoding($inputfile,"Shift-JIS");
$process = proc_open($mecabpath, $descriptorspec, $pipes);
if(is_resource($process)) {
fwrite($pipes[0], $inputfile);
fclose($pipes[0]);
/*よくサイトにのっている読み込みの方法例。1行ごとに配列に格納したかったので、ここではfgetsを使用。
パターン1.$result = stream_get_contents($pipes[1]);
パターン2.while (!feof($pipes[1])) { $result .= fread($pipes[1], 4096);}
*/
while(!feof($pipes[1])){
$result[] = fgets($pipes[1]);
}
fclose($pipes[1]);
proc_close($process);
//print_r($result); $resultにはmecabの実行結果が1行ずつ配列に格納されている。$result[0]が1行目。
}
foreach($result as $value) {
$word = explode("\t",$value); //mecabは最初の文字は空白ではなく、\tで仕切られているので注意。
echo $word[0].'<br>'; //1行ずつ単語のみが表示される
}
テキストファイルを作って、純粋にexecで実行するのであれば、
$txt = 'C:\sample\テキストまでのパス.txt';
exec("$mecabpath $txt",$result);
print_r($result);
と書くだけでよく、文字コードをわざわざ変換しなくてもうまくいく。
最終更新:2008年12月30日 12:37