中文分词的php代码_PHP教程

WBOY
Freigeben: 2016-07-20 11:10:01
Original
752 Leute haben es durchsucht

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

class NLP{
private static $cmd_path;
// 不以'/'结尾
static function set_cmd_path($path){
self::$cmd_path = $path;
}
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 编译后的可执行文件和词典在当前目录):
复制代码 代码如下:
require_once('NLP.php');
var_dump(NLP::tokenize('Hello, World!'));
?>

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

 


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/444764.htmlTechArticle以前有用过dedecms分词功能,经过测试还是不理想,后来经过一些处理得到的结果还是可以接受的,今天我再看到这款分词法,拿出来给大家...
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!