teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

疑似コードを追加。

2015/02/26 02:30

投稿

shinosan
shinosan

スコア209

answer CHANGED
@@ -1,2 +1,60 @@
1
1
  proc_open()は子プロセスでコマンドを実行しパイプや仮想コンソールで処理をさせるので、mecab コマンドを呼び出してやれば作れそうですね。
2
- [MeCabのコマンドライン引数](http://www.mwsoft.jp/programming/munou/mecab_command.html)を[proc_open()の引数に渡して](http://manual.xwd.jp/function.proc-open.html)パイプを読み書きすれば、Mecab_Targgerに近い処理ができるかと。
2
+ [MeCabのコマンドライン引数](http://www.mwsoft.jp/programming/munou/mecab_command.html)を[proc_open()の引数に渡して](http://manual.xwd.jp/function.proc-open.html)パイプを読み書きすれば、Mecab_Targgerに近い処理ができるかと。
3
+
4
+ 以下は[このサイト](http://colo-ri.jp/develop/2011/04/mecab_php_mecab.html)を参考に書いた疑似コードです。動作確認はしてません。
5
+
6
+ ```lang-PHP
7
+ class MeCab_Tagger_dummy {
8
+ public $firstNode = null;
9
+ public function parseToNode($txt) {
10
+ $cmd = 'mecab '; // コマンドライン引数があったらここに追加する
11
+ $descriptorspec = array(
12
+ 0 => array("pipe", "r"), // stdin は、子プロセスが読み込むパイプです。
13
+ 1 => array("pipe", "w"), // stdout は、子プロセスが書き込むパイプです。
14
+ 2 => array("file", "/home/mecab-output.txt", "a") // はファイルで、そこに書き込みます。
15
+ );
16
+ $cwd = '/home';
17
+ $process = proc_open($cmd, $descriptorspec, $pipes, $cwd);
18
+
19
+ if (is_resource($process)) {
20
+ fwrite($pipes[0], $txt);
21
+ fclose($pipes[0]);
22
+
23
+ while ( ($line = fgets($pipes[1])) !== false ) {
24
+ $node = new MeCab_Node_dummy($this->firstNode,$line);
25
+ if ( $this->firstNode === null ) $this->firstNode = $node;
26
+ }
27
+ fclose($pipes[1]);
28
+
29
+ proc_close($process);
30
+ }
31
+ return $this->firstNode;
32
+ }
33
+ }
34
+ class MeCab_Node_dummy {
35
+ public function __construct(MeCab_Node_dummy $prev,$feature) {
36
+ $prev->next = $this;
37
+ $this->feature = $feature;
38
+ if ( $feature ) {
39
+ $columns = mb_split(',',$feature);
40
+ $this->surface = mb_split(' ',$columns[0]);
41
+ }
42
+ }
43
+ protected $next;
44
+ protected $feature;
45
+ protected $surface = '';
46
+ public function getNext() { return $this->next; }
47
+ public function getFeature() { return $this->feature; }
48
+ public function getSurface() { return $this->surface; }
49
+ }
50
+
51
+ $mecab = new MeCab_Tagger_dummy();
52
+ $txt = "現在MeCabにおいて、php_mecabを使わずproc_open()関数で、Mecab_Tagger オブジェクト(またはその機能を持ったオブジェクト)を生成したいと考えております。";
53
+ $meisi = array(); //名詞配列
54
+ for ( $node=$mecab->parseToNode($txt); $node; $node=$node->getNext() ) {
55
+ $meisi[] = $node->getSurface();
56
+ }
57
+ //名詞の重複削除
58
+ $meisi = array_unique($meisi);
59
+ print_r($meisi);
60
+ ```