程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php做的簡單中文分詞代碼

php做的簡單中文分詞代碼

編輯:關於PHP編程

中文搜索引擎來說, 中文分詞是整個系統最基礎的部分之一, 因為目前基於單字的中文搜索算法並不是太好. 當然, 本文不是要對中文搜索引擎做研究, 而是分享如果用 PHP 做一個站內搜索引擎. 本文是這個系統中的一篇

進行中文分詞的 PHP 類就在下面了, 用 proc_open() 函數來執行分詞程序, 並通過管道和其交互, 輸入要進行分詞的文本, 讀取分詞結果.

<?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,
                    );
                $tokens[] = $item;
            }
        }

        return $tokens;
    }
}
NLP::set_cmd_path(dirname(__FILE__));
?>
使用起來很簡單(確保 ICTCLAS 編譯後的可執行文件和詞典在當前目錄):

<?php
require_once('NLP.php');
var_dump(NLP::tokenize('你好啊, 世界!'));
?>


站長經驗,

如果想做到搜索引擎分詞,需要強大的詞庫及更智能化的漢語拼音以及寫法,習慣等功能庫。


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved