`

利用PHP扩展trie_filter做敏感词过滤

    博客分类:
  • PHP
 
阅读更多

PS:原创文章,如需转载,请注明出处,谢谢!     

本文地址:http://flyer0126.iteye.com/blog/1931212

 

      早就想研究下敏感词过滤问题,今天有些时间,正好实践一下。

      1. 安装:libdatrie (http://linux.thai.net/~thep/datrie/datrie.html#Download)

       

 tar zxf libdatrie-0.2.4.tar.gz 
 cd libdatrie-0.2.4 
 ./configure --prefix=/usr/local 
 make 
 make install

  

      2. 安装 trie_filter 扩展 (https://code.google.com/p/as3chat/downloads/detail?name=trie_filter-2011-03-21.tar.gz)

 tar zxf trie_filter-2011.03.21.tar.gz 
 cd trie_filter-2011.03.21 
 phpize (#/usr/local/php/bin/phpize ) 
 ./configure --with-php-config=/usr/local/php/bin/php-config 
 make 
 make install 

 

3. 修改 php.ini 文件,添加 trie_filter 扩展:extension=trie_filter.so,重启PHP。

   查看phpinfo发现trie_filter 扩展可用,如下图所示:


 4. 生成敏感词词典 (dpp 在 trie_filter-1.0.0 里面)

      将需要检测的敏感词写入一文本文件(如:mgc.txt),每行一个敏感词,然后使用dpp处理文本文件生成词典。

      规则:./dpp txt_file_path dict_file_path 

      示例:./dpp ~/mgc.txt mgc.dic 

 

5. 应用

<?php
/**
 * trie_filter 敏感词过滤示例
 * 
 * @author flyer0126
 * @since  2013/08/26
 **/

// 载入词典,成功返回一个 Trie_Filter 资源句柄,失败返回 NULL
$file = trie_filter_load('/usr/local/src/trie_filter/mgc.dic');
var_dump($file);
$str1 = '今天利用trie_filter做敏感词过滤示例';
$str2 = '今天利用trie_filter做过滤示例';
// 检测文本中是否含有词典中定义的敏感词(假设敏感词设定为:‘敏感词’)
$res1 = trie_filter_search($file, $str1);
$res2 = trie_filter_search($file, $str2);
echo $res1 ? '存在敏感词' : '不存在敏感词';
echo "<br/>";
echo $res2 ? '存在敏感词' : '不存在敏感词';

/**
resource(1) of type (Trie tree filter)
存在敏感词
不存在敏感词
**/

 

 

    对应 libdatrie-0.2.4.tar.gz 及 trie_filter-2011-03-21.tar.gz 已添加至附件中,有兴趣的可以拿走~

      

  • 大小: 7.9 KB
2
2
分享到:
评论
2 楼 flyer0126 2013-08-27  
vb2005xu 写道
性能咋样?

性能方面本人还没有测试,   网上找了下相关解释:此扩展的检测算法基于 Double Array Trie Tree,查找单一关键字的时间复杂度为 O(1),查找整段文本的时间复杂度为 O(n),n 为文本的长度,而且检测的速度不会因为敏感词的增加而降低。
1 楼 vb2005xu 2013-08-26  
性能咋样?

相关推荐

Global site tag (gtag.js) - Google Analytics