php字典分词,广告违禁词模块

2023年2月23日13:37:54

php版本8.0 laravel8

https://github.com/lizhichao/VicWord

composer require lizhichao/word

数据库存储违禁词

// 生成字典
public static function generateDict()
    {
        $path = self::getPath();
        if (!file_exists($path)) {
            file_put_contents($path, '');
        } else {
            unlink($path);
            file_put_contents($path, '');
        }
        $dict = new VicDict($path);

        $ad = AdDict::where('is_delete', GlobalCode::NORMAL)->get(['name']);
        if ($ad->count() > 0) {
            foreach ($ad as $v) {
                if (!empty($v->name)) {
                    $dict->add($v->name, 'n');
                }
            }
            //保存词库
            $dict->save();
        }
    }
	
	// 分词匹配字典
    public static function mateWord(string $word = '')
    {
        if (empty($word)) {
            throw new Exception('待匹配文字不能为空');
        }

        $path = self::getPath();
        if (!file_exists($path)) {
            self::generateDict();
        }
        $fc = new VicWord($path);

        $data = $fc->getWord($word);

        if (!empty($data)) {
            $mtch = [];
            foreach ($data as $k => $v) {
                if ($v['3'] == 1) {
                    $mtch[] = $v['0'];
                }
            }
            $newArr = [];
            foreach ($mtch as $value) {
                $newArr[] = sprintf("<font color='red'>%s</font>", $value);
            }

            $replaceData = str_replace($mtch, $newArr, $word);

            return $replaceData;
        } else {
            return $word;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
含有3种切分方法 getWord 长度优先切分 。最快 getShortWord 细粒度切分。比最快慢一点点 getAutoWord 自动切分 (在相邻做了递归) 。效果最好 可自定义典,自己添加语到库,库支持文本格式json和二级制格式igb 二进制格式典小,加载快 dict.igb含有175662个,欢迎大家补充语到 dict.txt ,格式(语 \t idf \t 性) idf 获取方法 百度搜索这个语 Math.log(100000001/结果数量),如果你有更好的方法欢迎补充。 性 [标点符号,名,动,形容,区别,代,数,量,副,介,连,助,语气,拟声,叹] 取index ;标点符号取0 三种分词结果对比 $fc = new VicWord('igb'); $arr = $fc->getWord('北京大学生喝进口红酒,在北京大学生活区喝进口红酒'); //北京大学|生喝|进口|红酒|,|在|北京大学|生活区|喝|进口|红酒 //$arr 是一个数组 每个单元的结构[语,语位置,性,这个语是否包含在典中] 这里只值列出了语 $arr = $fc->getShortWord('北京大学生喝进口红酒,在北京大学生活区喝进口红酒'); //北京|大学|生喝|进口|红酒|,|在|北京|大学|生活|区喝|进口|红酒 $arr = $fc->getAutoWord('北京大学生喝进口红酒,在北京大学生活区喝进口红酒'); //北京|大学生|喝|进口|红酒|,|在|北京大学|生活区|喝|进口|红酒 //对比 //qq的分词和百度的分词 http://nlp.qq.com/semantic.cgi#page2 http://ai.baidu.com/tech/nlp/lexical 分词速度 机器阿里云 Intel(R) Xeon(R) Platinum 8163 CPU @ 2.50GHz getWord 每秒140w字 getShortWord 每秒138w字 getAutoWord 每秒40w字 测试文本在百度百科拷贝的一段5000字的文本
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值