用户名:
密 码: 记住
您当前的位置:首页 > 网络编程 > php教程

php做的简单中文分词代码

时间:2015-01-23  来源:西部数据  作者:西部数据

中文搜索引擎来说,中文分词是整个系统最基础的部分之一,因为目前基于单字的中文搜索算法并不是太好,当然,本文不是要对中文搜索引擎做研究,而是分享如果用 PHP 做一个站内搜索引擎,本文是这个系统中的一篇.

进行中文分词的 PHP 类就在下面了,用 proc_open() 函数来执行分词程序,并通过管道和其交互,输入要进行分词的文本,读取分词结果.

  1. <?php 
  2. class NLP{ 
  3.     private static $cmd_path
  4.     // 不以'/'结尾 
  5.     static function set_cmd_path($path){ 
  6.         self::$cmd_path = $path
  7.     }//开源代码phpfensi.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.      * 进行分词, 返回词语列表. 
  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. ?> 

使用起来很简单(确保 ICTCLAS 编译后的可执行文件和词典在当前目录):

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

站长经验:如果想做到搜索引擎分词,需要强大的词库及更智能化的汉语拼音以及写法,习惯等功能库.

来顶一下
返回首页
返回首页
推荐资讯
WiFi太不安全:7岁女孩11分钟内入侵公共网络 WiFi太不安全:7岁女孩11分钟内入侵近期刚刚发布研究说WiFi网络能获得人们手机里多少私人信息,
不服跑个分?人工智能也出现“刷分”乱象 不服跑个分?人工智能也出现“刷分2014年,人工智能领域突然爆发,成为了科研和科技创业的热门
相关文章
    无相关信息
栏目更新
栏目热门