分词能干什么?
- 提取一篇文章的关键字
- 检测特定的段落中有没有违禁词
- 智能机器人
- …..尽你所想
开启SAE 分词服务
首先你需要在sae的管理面板开始分词服务后才能使用sae的服务。具体的开启操作:
成功的开启之后可以写一段脚本试试看看分词的效果如何,代码如下:
filename:test_segment.php
<?php header("Content-Type:text/html;charset=utf-8"); $str = '我是一个超级大懒鬼'; $seg = new SaeSegment(); $ret = $seg->segment($str, 1); var_dump($ret); ?>
访问 :http://lazydemo.sinaapp.com/segment/test_segment.php 发现输出:
array(6) { [0]=> array(3) { ["word"]=> string(3) "我" ["word_tag"]=> string(3) "123" ["index"]=> string(1) "0" } [1]=> array(3) { ["word"]=> string(3) "是" ["word_tag"]=> string(3) "173" ["index"]=> string(1) "1" } [2]=> array(3) { ["word"]=> string(6) "一个" ["word_tag"]=> string(3) "201" ["index"]=> string(1) "2" } [3]=> array(3) { ["word"]=> string(6) "超级" ["word_tag"]=> string(2) "20" ["index"]=> string(1) "3" } [4]=> array(3) { ["word"]=> string(3) "大" ["word_tag"]=> string(2) "10" ["index"]=> string(1) "4" } [5]=> array(3) { ["word"]=> string(6) "懒鬼" ["word_tag"]=> string(2) "95" ["index"]=> string(1) "5" } }
发现效果还不错,那么下面就是一个更综合的实例(来找一个网页中是否包含敏感词)来说明sae分词服务的应用。我们假设这里的敏感词只为几个,为了更简单的说明实例,在现实的应用中,可以把敏感词变成一个数组,推倒memcache中加速。我们假设此处的敏感词为:
array('fuck','av','苍老湿');
判断的脚本:
filename:segment_api.php
<?php header("Content-Type:text/html;charset=utf-8"); $str = $_REQUEST['str']; if($str == null) { die('没有链接哇'); } //获取指定链接的纯文本内容 $url_content = file_get_contents($str); $cotent_strip_tags = strip_tags($url_content);//过滤下HTML标签 $cotent_strip_tags = iconv("gb2312", "utf-8", $cotent_strip_tags);//转换编码 //var_dump($cotent_strip_tags); $seg = new SaeSegment(); $ret = $seg->segment($cotent_strip_tags,1,'utf-8'); foreach ($ret as $key) { $array_all[] = $key['word']; } $hot = array('fuck','av','苍老湿'); foreach($hot as $small) { if(in_array($small, $array_all)) { die('出现敏感词'); } } echo '未发现敏感词';
可以测试:http://lazydemo.sinaapp.com/segment/segment_api.php?str=http://www.php100.com
http://lazydemo.sinaapp.com/segment/segment_api.php?str=http://lazydemo.sinaapp.com/segment/hello.txt
其中hello.txt的内容是:
fuck av
本实例所有代码打包下载地址:
http://lazydemo.sinaapp.com/segment/segment.zip