基于DFA算法实现文章敏感词过滤

最近公司要出一个论坛系统
因为最近貌似xxx查的也比较严,所以图片和文字安全一样要注意
其中文字就涉及到敏感字过滤的问题
目前大概流传两种解决办法:
1、利用分词器分词实现过滤 比如见得比较多的 IKAnalyzer
2、利用一些效率优秀的算法 比如DFA算法
DFA算法 中文称作有穷自动机 解释:有一个有限状态集合和一些从一个状态通向另一个状态的边,每条边上标记有一个符号,其中一个状态是初态,某些状态是终态。
它是是通过event和当前的state得到下一个state,即event+state=nextstate。
至于为什么说DFA算法比较优秀,其实他也没做什么运算,有的只是状态的变化
ps:那好奇的宝宝说肯定就有无穷,详情见xxxdu。。。
下面用画图表示
比如现在有几个词需要被过滤
我是好人、我是坏蛋、我是学生

在这里插入图片描述
这样我们就把三个词变成了一棵树,以此类推 好多个词就变成了 几棵树
比如我的词库有2k多个词 可能100颗树?我猜的.
这样就大大减小了搜索的范围
以java的角度来看 他就是一个嵌套map 左边为键右边为值,嵌套进去,当get(key) == null 时说明到头了,这个时候如果全部匹配,说明你敏感了 要回家歇一会
理论差不多
具体实现还是有差异的
由于树可能到中间也是一个完整的词
所以不能以get(key)= null 为准 需要加一个标记 或者说转换状态来算作敏感。
下面上代码

package com.hqjl.communityserv.filter;

import com.hqjl.communityserv.util.SensitiveWordInit;

import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author chunying
 * @Date: 2019/9/26 0026
 */
public class SensitivewordFilter {

    @SuppressWarnings("rawtypes")
    private Map sensitiveWordMap = null;
    public static int minMatchTYpe = 1;      //最小匹配规则
    public static int maxMatchType = 2;      //最大匹配规则

    /**
     * 构造函数,初始化敏感词库
     */
    public SensitivewordFilter(File file){
        sensitiveWordMap = new SensitiveWordInit().initKeyWord(file);
    }

    /**
     * 判断文字是否包含敏感字符
     * @param txt  文字
     * @param matchType  匹配规则 1:最小匹配规则,2:最大匹配规则
     * @return 若包含返回true,否则返回false
     */
    public boolean isContaintSensitiveWord(String txt,int matchType){
        boolean flag = false;
        for(int i = 0 ; i < txt.length() ; i++){
            int matchFlag = this.CheckSensitiveWord(txt, i, matchType); //判断是否包含敏感字符
            if(matchFlag > 0){    //大于0存在,返回true
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 获取文字中的敏感词
     * @param txt 文字
     * @param matchType 匹配规则&nbsp;1:最小匹配规则,2:最大匹配规则
     * @return
     */
    public Set<String> getSensitiveWord(String txt , int matchType){
        Set<String> sensitiveWordList = new HashSet<String>();

        for(int i = 0 ; i < txt.length() ; i++){
            int length = CheckSensitiveWord(txt, i, matchType);    //判断是否包含敏感字符
            if(length > 0){    //存在,加入list中
                sensitiveWordList.add(txt.substring(i, i+length));
                i = i + length - 1;    //减1的原因,是因为for会自增
            }
        }

        return sensitiveWordList;
    }

    /**
     * 替换敏感字字符
     * @param txt
     * @param matchType
     * @param replaceChar 替换字符,默认*
     */
    public String replaceSensitiveWord(String txt,int matchType,String replaceChar){
        String resultTxt = txt;
        Set<String> set = getSensitiveWord(txt, matchType);     //获取所有的敏感词
        Iterator<String> iterator = set.iterator();
        String word = null;
        String replaceString = null;
        while (iterator.hasNext()) {
            word = iterator.next();
            replaceString = getReplaceChars(replaceChar, word.length());
            resultTxt = resultTxt.replaceAll(word, replaceString);
        }

        return resultTxt;
    }

    /**
     * 获取替换字符串
     * @param replaceChar
     * @param length
     * @return
     */
    private String getReplaceChars(String replaceChar,int length){
        String resultReplace = replaceChar;
        for(int i = 1 ; i < length ; i++){
            resultReplace += replaceChar;
        }

        return resultReplace;
    }

    /**
     * 检查文字中是否包含敏感字符,检查规则如下:<br>
     * @param txt
     * @param beginIndex
     * @param matchType
     * @return,如果存在,则返回敏感词字符的长度,不存在返回0
     */
    @SuppressWarnings({ "rawtypes"})
    public int CheckSensitiveWord(String txt,int beginIndex,int matchType){
        boolean  flag = false;    //敏感词结束标识位:用于敏感词只有1位的情况
        int matchFlag = 0;     //匹配标识数默认为0
        char word = 0;
        Map nowMap = sensitiveWordMap;
        for(int i = beginIndex; i < txt.length() ; i++){
            word = txt.charAt(i);
            nowMap = (Map) nowMap.get(word);     //获取指定key
            if(nowMap != null){     //存在,则判断是否为最后一个
                matchFlag++;     //找到相应key,匹配标识+1
                if("1".equals(nowMap.get("isEnd"))){       //如果为最后一个匹配规则,结束循环,返回匹配标识数
                    flag = true;       //结束标志位为true
                    if(SensitivewordFilter.minMatchTYpe == matchType){    //最小规则,直接返回,最大规则还需继续查找
                        break;
                    }
                }
            }
            else{     //不存在,直接返回
                break;
            }
        }
        if(matchFlag < 2 || !flag){        //长度必须大于等于1,为词
            matchFlag = 0;
        }
        return matchFlag;
    }
}


这里要用到一个初始化敏感词库的工具
package com.hqjl.communityserv.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author chunying
 * @Date: 2019/9/26 0026
 */
public class SensitiveWordInit {

    private final Logger logger = LoggerFactory.getLogger(SensitiveWordInit.class);

    public String ENCODING = "UTF-8";    //字符编码
    @SuppressWarnings("rawtypes")
    public HashMap sensitiveWordMap;

    public SensitiveWordInit(){
        super();
    }

    @SuppressWarnings("rawtypes")
    public Map initKeyWord(File file){
        try {
            //读取敏感词库
            Set<String> keyWordSet = readSensitiveWordFile(file);
            //将敏感词库加入到HashMap中
            addSensitiveWordToHashMap(keyWordSet);
            //spring获取application,然后application.setAttribute("sensitiveWordMap",sensitiveWordMap);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sensitiveWordMap;
    }

    /**
     * 读取敏感词库,将敏感词放入HashSet中,构建一个DFA算法模型:<br>
     * 我 = {
     *      isEnd = 0
     *      是 = {<br>
     *           isEnd = 1
     *           坏= {isEnd = 0
     *                人 = {isEnd = 1}
     *                }
     *           好  = {
     *                  isEnd = 0
     *                   人 = {
     *                        isEnd = 1
     *                       }
     *               }
     *           }
     *      }
     * @param keyWordSet  敏感词库
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private void addSensitiveWordToHashMap(Set<String> keyWordSet) {
        sensitiveWordMap = new HashMap(keyWordSet.size());     //初始化敏感词容器,减少扩容操作
        String key = null;
        Map nowMap = null;
        Map<String, String> newWorMap = null;
        //迭代keyWordSet
        Iterator<String> iterator = keyWordSet.iterator();
        while(iterator.hasNext()){
            key = iterator.next();    //关键字
            nowMap = sensitiveWordMap;
            for(int i = 0 ; i < key.length() ; i++){
                char keyChar = key.charAt(i);       //转换成char型
                Object wordMap = nowMap.get(keyChar);       //获取

                if(wordMap != null){        //如果存在该key,直接赋值
                    nowMap = (Map) wordMap;
                }
                else{     //不存在则,则构建一个map,同时将isEnd设置为0,因为他不是最后一个
                    newWorMap = new HashMap<String,String>();
                    newWorMap.put("isEnd", "0");     //不是最后一个
                    nowMap.put(keyChar, newWorMap);
                    nowMap = newWorMap;
                }

                if(i == key.length() - 1){
                    nowMap.put("isEnd", "1");    //最后一个
                }
            }
        }
    }

    /**
     * 读取敏感词库中的内容,将内容添加到set集合中
     */
    @SuppressWarnings("resource")
    private Set<String> readSensitiveWordFile(File file) throws Exception{
        Set<String> set = null;

        InputStreamReader read = new InputStreamReader(new FileInputStream(file),ENCODING);
        try {
            if(file.isFile() && file.exists()){      //文件流是否存在
                set = new HashSet<String>();
                BufferedReader bufferedReader = new BufferedReader(read);
                String txt = null;
                while((txt = bufferedReader.readLine()) != null){    //读取文件,将文件内容放入到set中
                    set.add(txt);
                }
            }
            else{         //不存在抛出异常信息
                throw new Exception("敏感词库文件不存在");
            }
        } catch (Exception e) {
            throw e;
        }finally{
            read.close();     //关闭文件流
        }
        return set;
    }
}


这里说下最小匹配原则 用于发现敏感词就算违规的系统,当发现含有敏感词时直接返回
最大匹配原则 当发现敏感词时继续查看 适用于后续需要替换敏感词

然后看下文章过滤是怎么用的
首先是baseFilter

package com.hqjl.communityserv.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;

/**
 * @author chunying
 * @Date: 2019/10/8 0008
 */
@Component
public class BaseFilter<T> {
    private final Logger LOG = LoggerFactory.getLogger(BaseFilter.class);

    private static File file;
    private static SensitivewordFilter secondFilter;
    private static SensitivewordFilter firetFilter;


    private T t;

    protected SensitivewordFilter getSecondFilter() {
        return secondFilter;
    }

    protected SensitivewordFilter getFiretFilter() {
        return firetFilter;
    }

    public void setT(T t) {
        this.t = t;
    }

    protected T getT() {
        return t;
    }

    public BaseFilter() {
    }

    @PostConstruct
    private synchronized void init() {
        if (firetFilter== null) {
            LOG.warn("正在初始化敏感词库...");
            file = new 	File(BaseFilter.class.getClassLoader().getResource("file/SensitiveWord.txt").getFile());
            firetFilter = new SensitivewordFilter(file);
        }
    }

    public FilterCheckResult checkViolation() {
        return null;
    }
}

创建baseFilter的原因是 我的程序中有好多需过滤的地方,其他filter需要继承它
其中SensitiveWord.txt 是放在resource下的敏感词文件
这个类的作用是项目启动时初始化了敏感词库,初始化以后不用再次读取敏感词文件了
这里我预留了两个filter,可以用作敏感1级 、2级的区分

然后是articleFilter

package com.hqjl.communityserv.filter;

import com.hqjl.communityserv.bean.po.Article;
import com.hqjl.communityserv.imageCheck.BaseRequest;
import com.hqjl.communityserv.imageCheck.ImageSyncScanRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author chunying
 * @Date: 2019/10/8 0008
 *
 * @Description:帖子的过滤器 用于帖子的内容校验以及违规检查
 */
@Component
public class ArticleFilter<T extends Article> extends BaseFilter{

    private final Logger LOG = LoggerFactory.getLogger(ArticleFilter.class);

    public ArticleFilter() {
    }

    public FilterCheckResult checkFormat() {
        FilterCheckResult filterCheckResult = new FilterCheckResult();
        Boolean result;
        T t = (T)super.getT();
        String content = t.getContent();
        String title = t.getTitle();
        if (StringUtils.isEmpty(content.trim())) {
            LOG.warn("该帖子内容为空" + t.getTitle());
            result = false;
        }
    
        result = true;
        filterCheckResult.setResult(result);
        return filterCheckResult;
    }

    @Override
    public FilterCheckResult checkViolation() {
        FilterCheckResult filterCheckResult = new FilterCheckResult();
        String detail = "";
        Boolean result = true;
        filterCheckResult.setResult(result);
        filterCheckResult.setDetail(detail);
        if(!(checkFormat().getResult())) {
            result = false;
            return filterCheckResult;
        }
        T t = (T)getT();
        String content = t.getContent();
        String title = t.getTitle();
        String label = t.getLabel();
        boolean b3 = false;

        //敏感词过滤  TODO 双层filter过滤
        SensitivewordFilter filter = getFiretFilter();
        boolean b1 = filter.isContaintSensitiveWord(content, 1);
        if (label != null) {
            b3 = filter.isContaintSensitiveWord(label, 1);
        }
        //替换敏感字
        if (b1) {
            content = filter.replaceSensitiveWord(content, 1, "*") ;
            detail += "帖子正文有敏感词";
        }
        if (b3 && label != null) {
            filter.replaceSensitiveWord(label, 1, "*") ;
            detail += "话题有敏感词";
        }   
        t.setContent(content);
        t.setLabel(label);
        if (b1 || b3) {
            result = false;
        }
        filterCheckResult.setResult(result);
        filterCheckResult.setDetail(detail);
        return filterCheckResult;
    }


}

这里写的有点乱 不要介意,具体的article类我就不往这里放了 仅供参考
我这里是只要看到敏感词直接返回false 前端发帖失败
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章