以前有用過dedecms分詞功能,經過測試還是不理想,后來經過一些處理得到的結果還是可以接受的,今天我再看到這款分詞法,拿出來給大家看看,實例代碼如下:
- <?php
- class NLP{
- private static $cmd_path;
- // 不以'/'結尾
- static function set_cmd_path($path){
- self::$cmd_path = $path;
- }
- private function cmd($str){
- $descriptorspec = array(
- 0 => array("pipe", "r"),
- 1 => array("pipe", "w"),
- );
- $cmd = self::$cmd_path . "/ictclas";
- $process = proc_open($cmd, $descriptorspec, $pipes);
- if (is_resource($process)) {
- $str = iconv('utf-8', 'gbk', $str);
- fwrite($pipes[0], $str);
- $output = stream_get_contents($pipes[1]);
- fclose($pipes[0]);
- fclose($pipes[1]);
- $return_value = proc_close($process);
- }
- /*
- $cmd = "printf '$input' | " . self::$cmd_path . "/ictclas";
- exec($cmd, $output, $ret);
- $output = join("n", $output);
- */
- $output = trim($output);
- $output = iconv('gbk', 'utf-8', $output);
- return $output;
- }
- /**
- * 進行分詞, 返回詞語列表.
- */
- function tokenize($str){
- $tokens = array();
- $output = self::cmd($input);
- if($output){
- $ps教程 = preg_split('/s+/', $output);
- foreach($ps as $p){
- list($seg, $tag) = explode('/', $p);
- $item = array(
- 'seg' => $seg,
- 'tag' => $tag,
- ); //開源代碼Vevb.com
- $tokens[] = $item;
- }
- }
- return $tokens;
- }
- }
- NLP::set_cmd_path(dirname(__FILE__));
- ?>
用起來很簡單,確保 ICTCLAS 編譯后的可執(zhí)行文件和詞典在當前目錄,代碼如下:
- <?php
- require_once('NLP.php');
- var_dump(NLP::tokenize('Hello, World!'));
- ?>
進行中文分詞的 PHP 類就在下面了,用 proc_open() 函數來執(zhí)行分詞程序,并通過管道和其交互, 輸入要進行分詞的文本, 讀取分詞結果.
新聞熱點
疑難解答