Java使用DFA算法处理敏感词汇_java dfa算法 + redis-程序员宅基地

技术标签: 算法  java  开源分享项目  后台  intellij-idea  dfa算法  springboot  开发语言  

1. 初始化敏感词库,将敏感词加入到HashMap中,构建DFA算法模型

package com.datago.common.utils.sensitive;


import java.util.*;

/**
 * @ProjectName innovate  初始化敏感词库,将敏感词加入到HashMap中,构建DFA算法模型
 * @Package com.datago.common.utils.sensitive
 * @Name SensitiveWordInit
 * @Author HB
 * @Date 2022/1/25 18:12
 * @Version 1.0
 */

public class SensitiveWordInit {
    
    @SuppressWarnings("rawtypes")
    public static HashMap sensitiveWordMap;

    public SensitiveWordInit() {
    
        super();
    }

    /**
     * 初始化词库
     *
     * @param datas 敏感词集合
     * @return
     */
    public static HashMap init(String datas) {
    
        addSensitiveWord(datas);
        return sensitiveWordMap;
    }

    private static void addSensitiveWord(String word) {
    
        sensitiveWordMap = new HashMap(word.length());
        Map<String, Object> now = null;
        Map now2 = null;
            now2 = sensitiveWordMap;
            for (int i = 0; i < word.length(); i++) {
    
                char key_word = word.charAt(i);
                Object obj = now2.get(key_word);
                if (obj != null) {
     //存在
                    now2 = (Map) obj;
                } else {
     //不存在
                    now = new HashMap<>();
                    now.put("isEnd", "0");
                    now2.put(key_word, now);
                    now2 = now;
                }
                if (i == word.length() - 1) {
    
                    now2.put("isEnd", "1");
                }
            }
    }

    /**
     * 获取内容中的敏感词
     *
     * @param text      内容
     * @param matchType 匹配规则 1=不最佳匹配,2=最佳匹配
     * @return
     */
    public static List<String> getSensitiveWord(String text, int matchType) {
    
        List<String> words = new ArrayList<String>();
        Map now = sensitiveWordMap;
        int count = 0;  //初始化敏感词长度
        int start = 0; //标志敏感词开始的下标
        for (int i = 0; i < text.length(); i++) {
    
            char key = text.charAt(i);
            now = (Map) now.get(key);
            if (now != null) {
     //存在
                count++;
                if (count == 1) {
    
                    start = i;
                }
                if ("1".equals(now.get("isEnd"))) {
     //敏感词结束
                    now = sensitiveWordMap; //重新获取敏感词库
                    words.add(text.substring(start, start + count)); //取出敏感词,添加到集合
                    count = 0; //初始化敏感词长度
                }
            } else {
     //不存在
                now = sensitiveWordMap;//重新获取敏感词库
                if (count == 1 && matchType == 1) {
     //不最佳匹配
                    count = 0;
                } else if (count == 1 && matchType == 2) {
     //最佳匹配
                    words.add(text.substring(start, start + count));
                    count = 0;
                }
            }
        }
        return words;
    }
}

2. 敏感词过滤

package com.datago.common.utils.sensitive;

import com.datago.common.core.redis.RedisCache;
import com.datago.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @ProjectName innovate 敏感词过滤
 * @Package com.datago.common.utils.sensitive
 * @Name SensitivewordFilter
 * @Author HB
 * @Date 2022/1/25 18:14
 * @Version 1.0
 */

@Component
public class SensitivewordFilter {
    


    private static RedisCache redisCache;

    @Autowired
    public void setRedisCache(RedisCache redisCache) {
    
        SensitivewordFilter.redisCache = redisCache;
    }

    @SuppressWarnings("rawtypes")
    private static Map sensitiveWordMap = null;


    public static void initSensitiveWord(String datas) {
    
        sensitiveWordMap = SensitiveWordInit.init(datas);
    }

    /**
     * 替换敏感字字符
     *
     * @param txt
     * @param matchType
     * @param replaceChar 替换字符,默认*
     * @author HB
     * @version 1.0
     */
    public static String replaceSensitiveWord(String datas, String txt, int matchType, String replaceChar) {
    
        if (sensitiveWordMap == null) {
    
            initSensitiveWord(datas);
        }
        String resultTxt = txt;
        //matchType = 1;      //最小匹配规则
        //matchType= 2;      //最大匹配规则
        List<String> set = SensitiveWordInit.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
     * @author HB
     * @version 1.0
     */
    private static String getReplaceChars(String replaceChar, int length) {
    
        String resultReplace = replaceChar;
        if (length > 6) {
    
            length = 6;
        }
        for (int i = 1; i < length; i++) {
    
            resultReplace += replaceChar;
        }
        return resultReplace;
    }


    /**
     * 过滤敏感词汇
     *
     * @param sensitiveTxt 输入数据
     * @return com.datago.common.core.domain.AjaxResult
     * @Author HB
     * @Date 2022/1/27 10:03
     **/
    public static String filterSensitive(String sensitiveTxt) {
    
        //从缓存中提取数据敏感词汇
        Map<String, String> datas = redisCache.getCacheObject("treeSensitive");
        //替换敏感词汇
        String updateTxt = null;
        for (Map.Entry<String, String> entry : datas.entrySet()) {
    
            SensitivewordFilter.initSensitiveWord(entry.getKey());
            if (StringUtils.isNotEmpty(updateTxt)) {
    
                updateTxt = replaceSensitiveWord(entry.getKey(), updateTxt, 1, entry.getValue());
            } else {
    
                updateTxt = replaceSensitiveWord(entry.getKey(), sensitiveTxt, 1, entry.getValue());
            }
        }
        return updateTxt;
    }

}


3.应用

   /**
     * 过滤datago_sensitive敏感词汇
     * sensitiveTxt  传参
     */
    @Log(title = "过滤敏感词汇")
    @GetMapping("/filterSensitive/{sensitiveTxt}")
    public AjaxResult filterSensitive(@PathVariable(value = "sensitiveTxt") String sensitiveTxt) {
    
        String s = SensitivewordFilter.filterSensitive(sensitiveTxt);
        return AjaxResult.success(s);
    }

4.参考文献

https://www.hutool.cn/docs/#/dfa/DFA%E6%9F%A5%E6%89%BE
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sinat_37239798/article/details/122893173

智能推荐

个人笔记之rabbitTemplate及amqpTemplate发布模式-程序员宅基地

文章浏览阅读3.5w次,点赞15次,收藏90次。rabbitTemplate及amqpTemplate发布模式不足之处欢迎留言1、rabbitTemplate和amqpTemplate有什么关系?源码中会发现rabbitTemplate实现自amqpTemplate接口,使用起来并无区别,需引入spring-boot-starter-amqp依赖。2、组成生产者 消息队列 消费者 交换机: 隔离生产者和消息队列,充当二者..._amqptemplate

golang 学习(二十五)go mod以及自定义包package的用法和init()方法_go mod init-程序员宅基地

文章浏览阅读1.8w次,点赞11次,收藏44次。go mod以及自定义包package的用法和init()方法包的介绍和定义包(packge)是多个 Go 源码的集合,是一种高级的代码复用方案,Go 语言为我们提供了 很多内置包,如:fmt、strconv、strings、sort、eros、time、encoding/json、os、io 等。Golang 中的包可以分为三种:1、系统内置包 2、自定义包 3、第三方包 系统内置包: Golang语言给我们提供的内置包,引入后可以直接使用,如 fmt、srconv、strings、sort、e_go mod init

c++使用vector创建二维0矩阵(初始化)_c++ 二维vector初始化为0-程序员宅基地

文章浏览阅读7.1k次,点赞7次,收藏43次。c++使用vector创建二维0矩阵(初始化)一、前言c++真的是又爱又恨的一门语言,本人是一名python程序员但是因工作需求不得不投入到c++的大军中,逐渐偏离人生苦短我用python的初衷,唠叨完毕开始正题。最近在做一个去eigen库的工作,需要使用vector替换,于是总结了一些使用vector实现矩阵的一些操作的代码,有需要的可以借鉴一下(亲测可用哦)。本篇仅仅写的是vector的初始化的方法,文章后面会逐渐附上其他矩阵操作的链接。二、话不多说上才艺开始我刚使用vector的时候_c++ 二维vector初始化为0

Solr 与 lucene-程序员宅基地

文章浏览阅读1.1k次。1、开篇语2、概述3、渊源4、初识Solr5、Solr的安装6、Solr分词顺序7、Solr中文应用的一个实例8、Solr的检索运算符[开篇语]按照惯例应该写一篇技术文章了,这次结合Lucene/Solr来分享一下开发经验。Lucene是一个使用Java语言写的全文检索开发包(API),利用它可以实现强大的检索功能,它的详细介绍大家可以去Google上搜索一下,本文重点放在Solr相关的讨

OpenCVSharp 4.5 仿射变换_仿射线程 opencvsharp-程序员宅基地

文章浏览阅读1.2k次。用OpenCVSharp4.5跑一遍OpenCV官方教程原教程链接:https://docs.opencv.org/4.5.0/d4/d61/tutorial_warp_affine.html核心函数:warpAffine,getRotationMatrix2Dusing System;using OpenCvSharp;namespace ConsoleApp1{ class tutorial18 : ITutorial { public void.._仿射线程 opencvsharp

C - Cat Snuke and a Voyage(dfs)-程序员宅基地

文章浏览阅读176次。题目链接:https://atcoder.jp/contests/arc079/tasks/arc079_a题意:给你n个点m条边;问你是否存在一条从1到n的长度为2的边;代码:#include<iostream>#include<cstring>#include<cmath>#include<cstdio>using...

随便推点

Vivado HLS 三:基本概念(lut、latch、ff、RAM、ROM、FIFO等)_vivado ff-程序员宅基地

文章浏览阅读1w次,点赞14次,收藏87次。Vivado HLS 三:基本概念参考:https://blog.csdn.net/wordwarwordwar/article/details/79998130http://www.elecfans.com/d/663922.html目录:1、FPGA中LUT、LATCH、FF的概念2、LUT、LATCH、FF的相互关系3、verilog语句与LUT、LATCH、FF的对应关系1、FPGA中LUT、LATCH、FF的概念LUT(look up table):查找表 .._vivado ff

2022年全球市场箱式穿梭车总体规模、主要生产商、主要地区、产品和应用细分研究报告_穿梭车数量预测分析-程序员宅基地

文章浏览阅读926次。本文研究全球市场、主要地区和主要国家箱式穿梭车的销量、销售收入等,同时也重点分析全球范围内主要厂商(品牌)竞争态势,箱式穿梭车销量、价格、收入和市场份额等。_穿梭车数量预测分析

Java实现二维数组遍历_java遍历二维数组连接线-程序员宅基地

文章浏览阅读1.1w次,点赞14次,收藏41次。1 使用普通for循环的方式int[][] chessArr1=new int[11][11]; chessArr1[1][2]=1; chessArr1[2][4]=2; for(int i=0;i<chessArr1.length;i++){ //先遍历行 for(int j=0;j..._java遍历二维数组连接线

NGSIM数据集Python处理(超车变道数据筛选)_iloc[lst_c[j]]-程序员宅基地

文章浏览阅读1.4k次,点赞2次,收藏10次。NGSIM数据集因其量大质优,在车辆跟驰、变道等领域的研究中被广泛使用,作为一种特殊的变道行为,超车变道存在其显著的特点,但对超车变道的研究较少,一方面,超车变道数据的获取存在一定难度,另一方面,超车变道的决策较为复杂,本文通过Python代码的编写,实现对NGSIM数据集中产生超车变道行为的车辆数据进行提取,以下概述代码主体部分及部分说明。如需完整代码,可点击本人上传的代码链接进行下载。NGSIM数据集超车变道数据筛选-数据挖掘文档类资源-CSDN文库获取每一车辆切割索引数据通过原始..._iloc[lst_c[j]]

C++中运算符重载(复数类定义和运算实现)_复数类定义及运算符重载-程序员宅基地

文章浏览阅读574次。运算符重载一般形式<类型><类名>::operator <操作符>(<参数表>){ ...}#include <iostream>using namespace std;class Complex{ double m_fReal,m_fImag;public: Complex(double r = 0, double i = 0):m_fReal(r),m_fImag(i){} double Real(){_复数类定义及运算符重载

c++调用python numpy编程_c++ numpy-程序员宅基地

文章浏览阅读1.7w次,点赞14次,收藏101次。背景现在用c++重构了python工程,有一部分后处理不想再花时间重构了,所以直接拿过来调用。边搜资料边做的,做这个demo花了些时间,所以记下来以防忘记。资料找了很多的c++调用python的方法,首先可以肯定的有不止一种方式,直接使用python库、numpy arrayobject库来做;另外一种是使用boost/python boost/numpy的方式。后一种没有调通,是链接库的问..._c++ numpy

推荐文章

热门文章

相关标签