使用php扩展trie_filter,利用词库,过滤敏感词

原文地址:使用php扩展trie_filter,利用词库,过滤敏感词



关键词过滤扩展,用于检查一段文本中是否出现敏感词,基于Double-Array Trie 树实现。


安装步骤

下面的$LIB_PATH为依赖库安装目录,$INSTALL_PHP_PATH为PHP5安装目录。


安装libdatrie依赖库

Bash
$ tar zxvf libdatrie-0.2.4.tar.gz
$ cd libdatrie-0.2.4
$ make clean
$ ./configure --prefix=$LIB_PATH
$ make
$ make install


安装trie_filter扩展 (https://github.com/wulijun/php-ext-trie-filter)

Bash
$ $INSTALL_PHP_PATH/bin/phpize
$ ./configure --with-php-config=$INSTALL_PHP_PATH/bin/php-config --with-trie_filter=$LIB_PATH
$ make
$ make install

然后修改php.ini,增加一行:extension=trie_filter.so,然后重启PHP。


PHP测试实例

PHP
<?php
ini_set('memory_limit', '512M');
$arrWord = file('dict.txt');

$resTrie = trie_filter_new();

foreach ($arrWord as $k => $v) {
    trie_filter_store($resTrie, $v);
}
trie_filter_save($resTrie, __DIR__ . '/blackword.tree');
$resTrie = trie_filter_load(__DIR__ . '/blackword.tree');

$str = '王玉鹏的媳妇叫刘敏,王玉鹏的邮箱地址是wangyupeng@jiayuan.com,想不想知道他的QQ号呢?';
$arrRet = trie_filter_search_all($resTrie, $str);

print_all($str, $arrRet);

function print_all($str, $res) {//print_r($res);
    echo "$str\n";
    foreach ($res as $k => $v) {
        echo $k."=>{$v[0]}-{$v[1]}-".substr($str, $v[0], $v[1])."\n";
    }
}


测试效果,输出格式(顺序值=>该敏感词出现的位置-该敏感词的长度-敏感词)

执行效率,高高高,超级高,速度非常快。

QQ截图20151016232103.png


注意事项

dict.txt 为敏感词库,一个词一行

QQ截图20151016230827.png


优化建议

把文本词库生成tree的过程需要时间,该步骤可以异步实现,过滤过程只需要加载tree即刻。


PHP需要5.2以上版本


相关下载:

http://linux.thai.net/pub/thailinux/software/libthai/

https://github.com/wulijun/php-ext-trie-filter

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值