java敏感词过滤
  40IdLO25mCaU 2023年11月02日 22 0


java敏感词过滤

配置文件:

package com.wjg.mgcth.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Description
 * @Auther WangJinguo
 * @Date 2022/4/17 10:32
 * @Version 1.0
 **/
@Configuration
@SuppressWarnings({"rawtypes","unchecked"})
public class SensitiveWordInit {
    // 字符编码
    private String ENCODING = "UTF-8";
    // 初始化敏感字库
    public Map initKeyWord() throws IOException {
        // 读取敏感词库 ,存入Set中
        Set<String> wordSet = readSensitiveWordFile();
        // 将敏感词库加入到HashMap中//确定有穷自动机DFA
        return addSensitiveWordToHashMap(wordSet);
    }

    // 读取敏感词库 ,存入HashMap中
    private Set<String> readSensitiveWordFile() throws IOException {
        Set<String> wordSet = null;
        //敏感词的文件放在resources/static 文件夹下
        ClassPathResource classPathResource = new ClassPathResource("static/词库名称.txt");
        InputStream inputStream = classPathResource.getInputStream();
        //敏感词库
        try {
            // 读取文件输入流
            InputStreamReader read = new InputStreamReader(inputStream, ENCODING);
            // 文件是否是文件 和 是否存在
            wordSet = new HashSet<String>();
            // StringBuffer sb = new StringBuffer();
            // BufferedReader是包装类,先把字符读到缓存里,到缓存满了,再读入内存,提高了读的效率。
            BufferedReader br = new BufferedReader(read);
            String txt = null;
            // 读取文件,将文件内容放入到set中
            while ((txt = br.readLine()) != null) {
                wordSet.add(txt);
            }
            br.close();
            // 关闭文件流
            read.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wordSet;
    }
    // 将HashSet中的敏感词,存入HashMap中
    private Map addSensitiveWordToHashMap(Set<String> wordSet) {
        // 初始化敏感词容器,减少扩容操作
        Map wordMap = new HashMap(wordSet.size());
        for (String word : wordSet) {
            Map nowMap = wordMap;
            for (int i = 0; i < word.length(); i++) {
                // 转换成char型
                char keyChar = word.charAt(i);
                // 获取
                Object tempMap = nowMap.get(keyChar);
                // 如果存在该key,直接赋值
                if (tempMap != null) {
                    nowMap = (Map) tempMap;
                }
                // 不存在则,则构建一个map,同时将isEnd设置为0,因为他不是最后一个
                else {
                    // 设置标志位
                    Map<String, String> newMap = new HashMap<String, String>();
                    newMap.put("isEnd", "0");
                    // 添加到集合
                    nowMap.put(keyChar, newMap);
                    nowMap = newMap;
                }
                // 最后一个
                if (i == word.length() - 1) {
                    nowMap.put("isEnd", "1");
                }
            }
        }
        return wordMap;
    }
}

过滤工具类:

package com.wjg.mgcth.utils;

import com.wjg.mgcth.config.SensitiveWordInit;

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

/**
 * @Description
 * @Auther WangJinguo
 * @Date 2022/4/17 11:02
 * @Version 1.0
 **/
//敏感词过滤器:利用DFA算法  进行敏感词过滤
public class SensitiveFilter {
    //敏感词过滤器:利用DFA算法  进行敏感词过滤
    private Map sensitiveWordMap = null;

    // 最小匹配规则
    public static int minMatchType = 1;

    // 最大匹配规则
    public static int maxMatchType = 2;

    // 单例
    private static SensitiveFilter instance = null;

    // 构造函数,初始化敏感词库
    private SensitiveFilter() throws IOException {
        sensitiveWordMap = new SensitiveWordInit().initKeyWord();
    }

    // 获取单例
    public static SensitiveFilter getInstance() throws IOException {
        if (null == instance) {
            instance = new SensitiveFilter();
        }
        return instance;
    }

    // 获取文字中的敏感词
    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);
            // 存在,加入list中
            if (length > 0) {
                sensitiveWordList.add(txt.substring(i, i + length));
                // 减1的原因,是因为for会自增
                i = i + length - 1;
            }
        }
        return sensitiveWordList;
    }
    // 替换敏感字字符
    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>
     * 如果存在,则返回敏感词字符的长度,不存在返回0
     * @param txt
     * @param beginIndex
     * @param matchType
     * @return
     */
    public int CheckSensitiveWord(String txt, int beginIndex, int matchType) {
        // 敏感词结束标识位:用于敏感词只有1位的情况
        boolean flag = false;
        // 匹配标识数默认为0
        int matchFlag = 0;
        Map nowMap = sensitiveWordMap;
        for (int i = beginIndex; i < txt.length(); i++) {
            char word = txt.charAt(i);
            // 获取指定key
            nowMap = (Map) nowMap.get(word);
            // 存在,则判断是否为最后一个
            if (nowMap != null) {
                // 找到相应key,匹配标识+1
                matchFlag++;
                // 如果为最后一个匹配规则,结束循环,返回匹配标识数
                if ("1".equals(nowMap.get("isEnd"))) {
                    // 结束标志位为true
                    flag = true;
                    // 最小规则,直接返回,最大规则还需继续查找
                    if (SensitiveFilter.minMatchType == matchType) {
                        break;
                    }
                }
            }
            // 不存在,直接返回
            else {
                break;
            }
        }

        if (SensitiveFilter.maxMatchType == matchType){
            if(matchFlag < 2 || !flag){        //长度必须大于等于1,为词
                matchFlag = 0;
            }
        }
        if (SensitiveFilter.minMatchType == matchType){
            if(matchFlag < 2 && !flag){        //长度必须大于等于1,为词
                matchFlag = 0;
            }
        }
        return matchFlag;
    }
}

测试类:

package com.wjg.mgcth.controller;

import com.wjg.mgcth.utils.SensitiveFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @Description
 * @Auther WangJinguo
 * @Date 2022/4/17 10:27
 * @Version 1.0
 **/
@RestController
public class MgcthController {
    @RequestMapping("/cs")
    public void cs(){
        try {
            SensitiveFilter sensitiveFilter = SensitiveFilter.getInstance();
            int wshi = sensitiveFilter.CheckSensitiveWord("敏感词", 0, 1);
            System.out.println("---------"+wshi);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

项目文件层级:

java敏感词过滤_敏感词


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  Fv5flEkOgYS5   2023年11月02日   49   0   0 i++javaide
40IdLO25mCaU