国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 開發(fā) > PHP > 正文

php做的簡(jiǎn)單中文分詞代碼

2024-05-04 21:48:50
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

中文搜索引擎來(lái)說(shuō),中文分詞是整個(gè)系統(tǒng)最基礎(chǔ)的部分之一,因?yàn)槟壳盎趩巫值闹形乃阉魉惴ú⒉皇翘?當(dāng)然,本文不是要對(duì)中文搜索引擎做研究,而是分享如果用 PHP 做一個(gè)站內(nèi)搜索引擎,本文是這個(gè)系統(tǒng)中的一篇.

進(jìn)行中文分詞的 PHP 類就在下面了,用 proc_open() 函數(shù)來(lái)執(zhí)行分詞程序,并通過(guò)管道和其交互,輸入要進(jìn)行分詞的文本,讀取分詞結(jié)果.

  1. <?php 
  2. class NLP{ 
  3.     private static $cmd_path
  4.     // 不以'/'結(jié)尾 
  5.     static function set_cmd_path($path){ 
  6.         self::$cmd_path = $path
  7.     }//開源代碼Vevb.com 
  8.     private function cmd($str){ 
  9.         $descriptorspec = array
  10.            0 => array("pipe""r"), 
  11.            1 => array("pipe""w"), 
  12.         ); 
  13.         $cmd = self::$cmd_path . "/ictclas"
  14.         $process = proc_open($cmd$descriptorspec$pipes); 
  15.         if (is_resource($process)) { 
  16.             $str = iconv('utf-8''gbk'$str); 
  17.             fwrite($pipes[0], $str); 
  18.             $output = stream_get_contents($pipes[1]); 
  19.             fclose($pipes[0]); 
  20.             fclose($pipes[1]); 
  21.             $return_value = proc_close($process); 
  22.         } 
  23.         /* 
  24.         $cmd = "printf '$input' | " . self::$cmd_path . "/ictclas"; 
  25.         exec($cmd, $output, $ret); 
  26.         $output = join("n", $output); 
  27.         */ 
  28.         $output = trim($output); 
  29.         $output = iconv('gbk''utf-8'$output); 
  30.         return $output
  31.     } 
  32.     /** 
  33.      * 進(jìn)行分詞, 返回詞語(yǔ)列表. 
  34.      */ 
  35.     function tokenize($str){ 
  36.         $tokens = array(); 
  37.         $output = self::cmd($input); 
  38.         if($output){ 
  39.             $ps = preg_split('/s+/'$output); 
  40.             foreach($ps as $p){ 
  41.                 list($seg$tag) = explode('/'$p); 
  42.                 $item = array
  43.                     'seg' => $seg
  44.                     'tag' => $tag
  45.                     ); 
  46.                 $tokens[] = $item
  47.             } 
  48.         } 
  49.         return $tokens
  50.     } 
  51. NLP::set_cmd_path(dirname(__FILE__)); 
  52. ?> 

使用起來(lái)很簡(jiǎn)單(確保 ICTCLAS 編譯后的可執(zhí)行文件和詞典在當(dāng)前目錄):

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

站長(zhǎng)經(jīng)驗(yàn):如果想做到搜索引擎分詞,需要強(qiáng)大的詞庫(kù)及更智能化的漢語(yǔ)拼音以及寫法,習(xí)慣等功能庫(kù).

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 泽普县| 井陉县| 三穗县| 积石山| 师宗县| 伊春市| 三门县| 满洲里市| 布尔津县| 伊川县| 奉节县| 海南省| 广昌县| 西和县| 平顶山市| 乐业县| 湘潭县| 双牌县| 抚松县| 瓦房店市| 察隅县| 清丰县| 滦平县| 松阳县| 江源县| 镇赉县| 肥城市| 合作市| 积石山| 图片| 乡宁县| 得荣县| 云梦县| 西峡县| 宝应县| 普洱| 陆川县| 吉木乃县| 婺源县| 商河县| 江华|