php做的簡單中文分詞代碼_PHP教程

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

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

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 編譯後的可執行檔和詞典在目前的目錄):

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


站長經驗,

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


http://www.bkjia.com/PHPjc/444776.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/444776.htmlTechArticle中文搜尋引擎來說, 中文分詞是整個系統最基礎的部分之一, 因為目前基於單字的中文搜尋演算法並不是太好. 當然, 本文不是要對中文搜尋引...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.