国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 南宁市| 莆田市| 洪江市| 珠海市| 随州市| 五河县| 苏州市| 泽州县| 方山县| 临桂县| 偃师市| 咸丰县| 柘城县| 常山县| 连云港市| 东海县| 文山县| 共和县| 资阳市| 调兵山市| 铜川市| 道孚县| 城口县| 长治市| 巴中市| 大名县| 滨州市| 澄江县| 阿拉尔市| 伊宁市| 太保市| 延边| 府谷县| 白银市| 社会| 会同县| 庄浪县| 曲阳县| 房产| 即墨市| 定西市|