最模板 - 外贸网站建设,外贸网站模板

最模板

当前位置: 首页 > 建站教程 > php教程 >

中文分词的php代码

时间:2014-09-06 14:26来源:未知 作者:最模板zuimoban 点击:
以前有用过dedecms分词功能,经过测试还是不理想,后来经过一些处理得到的结果还是可以接受的,今天我再看到这款分词法,拿出来给大家看看,实例代码如下: ?php class NLP{ private static $cmd_p

以前有用过dedecms分词功能,经过测试还是不理想,后来经过一些处理得到的结果还是可以接受的,今天我再看到这款分词法,拿出来给大家看看,实例代码如下:

  1. <?php 
  2. class NLP{  
  3. private static $cmd_path;  
  4. // 不以'/'结尾  
  5. static function set_cmd_path($path){  
  6. self::$cmd_path = $path;  
  7. }  
  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. ); //开源代码vcphp.com 
  46. $tokens[] = $item;  
  47. }  
  48. }  
  49. return $tokens;  
  50. }  
  51. }  
  52. NLP::set_cmd_path(dirname(__FILE__));  
  53. ?> 

用起来很简单,确保 ICTCLAS 编译后的可执行文件和词典在当前目录,代码如下:

  1. <?php  
  2. require_once('NLP.php');  
  3. var_dump(NLP::tokenize('Hello, World!'));  
  4. ?> 

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

(责任编辑:最模板)
------分隔线----------------------------
栏目列表
推荐内容