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));}
}