当前位置: 首页 > news >正文

springboot集成sensitive-word实现敏感词过滤

文章目录

  • 敏感词过滤
  • 方案一:正则表达式
  • 方案二:基于DFA算法的敏感词过滤工具框架-sensitive-word
    • springboot集成sensitive-word
      • 步骤一:引入pom
      • 步骤二:自定义配置
      • 步骤三:自定义敏感词+白名单
      • 步骤四:核心方法测试

敏感词过滤

敏感词过滤通常是指从文本中检测并移除或替换掉被认为是不适当、冒犯性或违反特定社区准则的词汇。这个过程常用于在线平台、论坛、社交媒体和聊天系统等,以确保交流环境的健康和积极.

方案一:正则表达式

实现敏感词过滤.只适合于敏感词较少、文本量较少的场合,并且无法处理同音字、错别字等,案例:

public static void main(String[] args) {String text = "这是一个包含敏感词汇的文本,例如色情、赌博等。";String[] sensitiveWords = {"色情", "赌博"};for (String word : sensitiveWords) {text = filterSensitiveWords(text, word);}System.out.println("过滤后的文本: " + text);testSensitiveWordFrame();}/*** 方案一:正则表达式实现敏感词过滤.只适合于敏感词较少、文本量较少的场合,并且无法处理同音字、错别字等.** @param text* @param sensitiveWord* @return*/public static String filterSensitiveWords(String text, String sensitiveWord) {Pattern pattern = Pattern.compile(sensitiveWord);Matcher matcher = pattern.matcher(text);return matcher.replaceAll("***");}

方案二:基于DFA算法的敏感词过滤工具框架-sensitive-word

 * 6W+ 词库,且不断优化更新* 基于 DFA 算法,性能较好* 基于 fluent-api 实现,使用优雅简洁* 支持敏感词的判断、返回、脱敏等常见操作* 支持全角半角互换* 支持英文大小写互换* 支持数字常见形式的互换* 支持中文繁简体互换* 支持英文常见形式的互换* 支持用户自定义敏感词和白名单* 支持数据的数据动态更新,实时生效

springboot集成sensitive-word

步骤一:引入pom

<dependency><groupId>com.github.houbb</groupId><artifactId>sensitive-word</artifactId><version>0.2.0</version>
</dependency>

步骤二:自定义配置

@Configuration
public class MySensitiveWordBs {@Autowiredprivate MyWordAllow myWordAllow;@Autowiredprivate MyWordDeny myWordDeny;@Autowiredprivate MyWordReplace myWordReplace;/*** 初始化引导类** @return 初始化引导类* @since 1.0.0*/@Beanpublic SensitiveWordBs sensitiveWordBs() {SensitiveWordBs sensitiveWordBs = SensitiveWordBs.newInstance()
//                .wordAllow(WordAllows.chains(WordAllows.defaults(), myWordAllow)) // 设置多个敏感词,系统默认和自定义
//                .wordDeny(WordDenys.chains(WordDenys.defaults(), myWordDeny))     // 设置多个敏感词,系统默认和自定义.wordAllow(WordAllows.chains(myWordAllow))  // 自定义.wordDeny(WordDenys.chains(myWordDeny))     // 自定义.wordReplace(myWordReplace)                                        // 自定义替换规则.ignoreCase(true)           // 忽略大小写.ignoreWidth(true)          // 忽略半角圆角.ignoreNumStyle(true)       // 忽略数字的写法.ignoreChineseStyle(true)   // 忽略中文的书写格式.ignoreEnglishStyle(true)   // 忽略英文的书写格式.ignoreRepeat(true)         // 忽略重复词.enableNumCheck(true)       // 是否启用数字检测。默认连续 8 位数字认为是敏感词.enableEmailCheck(true)     // 是有启用邮箱检测.enableUrlCheck(true)       // 是否启用链接检测.init();return sensitiveWordBs;}
}

步骤三:自定义敏感词+白名单

/*** 自定义非敏感词* 注意每一行为一个非敏感词,单行不能只包括空格,否则,也会把空格识别为非敏感词*/
@Component
@Slf4j
public class MyWordAllow implements IWordAllow {@Overridepublic List<String> allow() {List<String> allowWords = new ArrayList<>();try {ClassPathResource resource = new ClassPathResource("myAllowWords.txt");Path myAllowWordsPath = Paths.get(resource.getUrl().toURI());allowWords = Files.readAllLines(myAllowWordsPath, StandardCharsets.UTF_8);} catch (IOException ioException) {log.error("读取非敏感词文件错误:{}", ioException);} catch (URISyntaxException e) {throw new RuntimeException(e);}return allowWords;}
}
@Component
@Slf4j
public class MyWordDeny implements IWordDeny {@Overridepublic List<String> deny() {List<String> denyWords = new ArrayList<>();try {ClassPathResource resource = new ClassPathResource("myDenyWords.txt");Path myAllowWordsPath = Paths.get(resource.getUrl().toURI());denyWords = Files.readAllLines(myAllowWordsPath, StandardCharsets.UTF_8);} catch (IOException ioException) {log.error("读取敏感词文件错误:{}", ioException);} catch (URISyntaxException e) {throw new RuntimeException(e);}return denyWords;}
}
/*** 自定义敏感词对应的替换值.* 场景说明:有时候我们希望不同的敏感词有不同的替换结果。比如【游戏】替换为【电子竞技】,【失业】替换为【灵活就业】。*/
@Configuration
public class MyWordReplace implements IWordReplace {@Overridepublic void replace(StringBuilder stringBuilder, final char[] rawChars, IWordResult wordResult, IWordContext wordContext) {String sensitiveWord = InnerWordCharUtils.getString(rawChars, wordResult);if ("zhupeng".equals(sensitiveWord)) {stringBuilder.append("朱鹏");} else {// 其他默认使用 * 代替int wordLength = wordResult.endIndex() - wordResult.startIndex();for (int i = 0; i < wordLength; i++) {stringBuilder.append('-');}}}
}

步骤四:核心方法测试

public class SensitiveWordController {@Autowiredprivate MyWordReplace myWordReplace;@Autowiredprivate SensitiveWordBs sensitiveWordBs;private static final String text = "五星红旗迎风飘扬,毛主席的画像屹立在天安门前,zhuzhuhzu";@GetMapping("/pattern")public void testSensitiveWord2() {String text = "这是一个包含敏感词汇的文本,例如色情、赌博等。";String[] sensitiveWords = {"色情", "赌博"};for (String word : sensitiveWords) {text = filterSensitiveWords(text, word);}System.out.println("过滤后的文本: " + text);}/*** 方案二:基于DFA算法的敏感词过滤工具框架-sensitive-word:https://github.com/houbb/sensitive-word* 6W+ 词库,且不断优化更新* 基于 DFA 算法,性能较好* 基于 fluent-api 实现,使用优雅简洁* 支持敏感词的判断、返回、脱敏等常见操作* 支持全角半角互换* 支持英文大小写互换* 支持数字常见形式的互换* 支持中文繁简体互换* 支持英文常见形式的互换* 支持用户自定义敏感词和白名单* 支持数据的数据动态更新,实时生效*/@GetMapping("/filter")public void testSensitiveWord() {System.out.println("SensitiveWordHelper.contains(text) = " + SensitiveWordHelper.contains(text));System.out.println("SensitiveWordHelper.findAll(text) = " + SensitiveWordHelper.findAll(text));System.out.println("SensitiveWordHelper.replace(text,myWordReplace) = " + SensitiveWordHelper.replace(text, myWordReplace));// 如果自定义敏感词,不要使用SensitiveWordHelper的方法,要使用SensitiveWordBsSystem.out.println("sensitiveWordBs.contains(text) = " + sensitiveWordBs.contains(text));System.out.println("sensitiveWordBs.findAll(text) = " + sensitiveWordBs.findAll(text));System.out.println("sensitiveWordBs.replace(text) = " + sensitiveWordBs.replace(text));}
}
http://www.lryc.cn/news/423475.html

相关文章:

  • C++ 之动手写 Reactor 服务器模型(一):网络编程基础复习总结
  • qt 在vs2022 报错记录
  • 【人工智能】TensorFlow和机器学习概述
  • SQLALchemy 的介绍
  • Java虚拟机:运行时内存结构
  • 微信小程序子组件调用父组件的方法
  • 【数据结构】TreeMap和TreeSet
  • 前端react集成OIDC
  • JavaWeb—XML_Tomcat10_HTTP
  • 中介者模式在Java中的实现:设计模式精解
  • PyQt编程快速上手
  • Docker Swarm管理
  • Python | Leetcode Python题解之第335题路径交叉
  • Ubuntu视频工具
  • HBase snapshot+replication 测试
  • 代码随想录算法训练营第四十一天|图论基础、深度优先搜索理论基础、98. 所有可达路径、797. 所有可能的路径
  • STM32学习笔记09-SPI通信
  • 树------二叉树
  • 如何对加密后的数据进行模糊查询(面试题)
  • 【MYSQL】当前读和快照读
  • C语言-使用数组法,指针法实现将一个5X5的矩阵中最大的元素放在中心,四个角分别放四个最小的元素(顺序为从左到右,从上到下,从小到大存放),写一函数实现之。
  • Android gradle 构建
  • vulnhub系列:devguru
  • Robot Operating System——高质量图像传输
  • NLP_情感分类_预训练加微调方案
  • 全网最适合入门的面向对象编程教程:36 Python的内置数据类型-字典
  • DataWind看板绘制案例
  • Golang | Leetcode Golang题解之第335题路径交叉
  • C# 在Word中插入或删除分节符
  • 基于STM32+Qt设计的无人超市收银系统(206)