中文搜尋引擎來說, 中文分詞是整個系統最基礎的部分之一, 因為目前基於單字的中文搜尋演算法並不是太好. 當然, 本文不是要對中文搜尋引擎做研究, 而是分享如果用 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中文搜尋引擎來說, 中文分詞是整個系統最基礎的部分之一, 因為目前基於單字的中文搜尋演算法並不是太好. 當然, 本文不是要對中文搜尋引...