加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php做的基础中文分词代码

发布时间:2022-02-15 16:59:34 所属栏目:PHP教程 来源:互联网
导读:中文搜索引擎来说,中文分词是整个系统最基础的部分之一,因为目前基于单字的中文搜索算法并不是太好,当然,本文不是要对中文搜索引擎做研究,而是分享如果用 PHP 做一个站内搜索引擎,本文是这个系统中的一篇. 进行中文分词的 PHP 类就在下面了,用 proc_open()
  中文搜索引擎来说,中文分词是整个系统最基础的部分之一,因为目前基于单字的中文搜索算法并不是太好,当然,本文不是要对中文搜索引擎做研究,而是分享如果用 PHP 做一个站内搜索引擎,本文是这个系统中的一篇.
 
  进行中文分词的 PHP 类就在下面了,用 proc_open() 函数来执行分词程序,并通过管道和其交互,输入要进行分词的文本,读取分词结果.
 
  <?php
  class NLP{
      private static $cmd_path;
      // 不以'/'结尾
      static function set_cmd_path($path){
          self::$cmd_path = $path;
      }//开源代码Cuoxin.com
      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 编译后的可执行文件和词典在当前目录):
 
  <?php
  require_once('NLP.php');
  var_dump(NLP::tokenize('你好啊, 世界!'));
  ?>
  站长经验:如果想做到搜索引擎分词,需要强大的词库及更智能化的汉语拼音以及写法,习惯等功能库.

(编辑:PHP编程网 - 黄冈站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读