Discuz教程网

PHP中文分词的简单实现代码分享

[复制链接]
authicon dly 发表于 2011-9-12 14:18:22 | 显示全部楼层 |阅读模式
当然, 本文不是要对中文搜索引擎做研究, 而是分享如果用 PHP 做一个站内搜索引擎。 本文是这个系统中的一篇。
我使用的分词工具是中科院计算所的开源版本的 ICTCLAS。 另外还有开源的 Bamboo, 我随后也会对该工具进行调研。
从 ICTCLAS 出发是个不错的选择, 因为其算法传播比较广泛, 有公开的学术文档, 并且编译简单, 库依赖少。 但目前只提供了 C/C++, Java 和 C# 版本的代码, 并没有 PHP 版本的代码。 怎么办呢? 也许可以学习它的 C/C++ 源码和学术文档中, 然后再开发一个 PHP 版本出来。 不过, 我要使用进程间通信, 在 PHP 代码里调用 C/C++ 版本的可执行文件。
下载源码解压后, 在有 C++ 开发库和编译环境的机器上直接 make ictclas 即可。 它的 Makefile 脚本有个错误, 执行测试的代码没有加上'。/', 当然不能像 Windows 下执行成功了。 但也不影响编译结果。
进行中文分词的 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. }
  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. }
  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中用hash实现的数组
下一篇:PHP 删除文件与文件夹操作 unlink()与rmdir()这两个函数的使用
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-2 06:54

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表