Discuz! 在线中文分词、关键词提取服务

不同于使用自己的服务器进行分词,Discuz!在线中文分词服务是基于API返回分词结果的。在项目中,我们只需要一个函数即可方便地进行分词、关键词提取。
以下是根据Discuz!在线分词服务API写的函数,测试可正常运行:

 1 /**
 2  * DZ在线中文分词
 3  * @param $title string 进行分词的标题
 4  * @param $content string 进行分词的内容
 5  * @param $encode string API返回的数据编码
 6  * @return  array 得到的关键词数组
 7  */
 8  function dz_segment($title = '', $content = '', $encode = 'utf-8'){
 9     if($title == ''){
10         return false;
11     }
12     $title = rawurlencode(strip_tags($title));
13     $content = strip_tags($content);
14     if(strlen($content)>2400){ //在线分词服务有长度限制
15         $content =  mb_substr($content, 0, 800, $encode);
16     }
17     $content = rawurlencode($content);
18     $url = 'http://keyword.discuz.com/related_kw.html?title='.$title.'&content='.$content.'&ics='.$encode.'&ocs='.$encode;
19     $xml_array=simplexml_load_file($url);                        //将XML中的数据,读取到数组对象中  
20     $result = $xml_array->keyword->result;
21     $data = array();
22     foreach ($result->item as $key => $value) {
23             array_push($data, (string)$value->kw);
24     }
25     if(count($data) > 0){
26         return $data;
27     }else{
28         return false;
29     }
30  }

分词示例,通过url访问:

1 http://keyword.discuz.com/related_kw.html?title=Discuz!在线中文分词、关键词提取服务&content=不同于使用自己的服务器进行分词,Discuz!在线中文分词服务是基于API返回分词结果的。在项目中,我们只需要一个函数即可方便地进行分词、关键词提取。&ics=utf-8&ocs=utf-8

得到的分词结果为:
关键词,服务器,在线,中文,项目

posted on 2014-07-28 17:03  wpjamer  阅读(1529)  评论(0编辑  收藏  举报

导航