zl程序教程

您现在的位置是:首页 >  其它

当前栏目

【敏感词过滤】

过滤 敏感
2023-09-27 14:29:28 时间

💝💝💝欢迎来到我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。

img

非常期待和您一起在这个小小的网络世界里共同探索、学习和成长。💝💝💝

✨✨ 欢迎订阅本专栏 ✨✨

1.引入工具包

sensitive-word 是一个 Java 编写的敏感词过滤工具包,可以用于对文本中的敏感词进行过滤。该工具包提供了多种敏感词匹配算法,并支持自定义敏感词库和替换策略。使用该工具包可以有效地保护用户隐私,防止不良信息的传播。 具体来说,sensitive-word 工具包提供了以下功能:

  1. 多种敏感词匹配算法,包括 DFA、AC 自动机等,可以根据实际需求选择合适的算法;
  2. 支持自定义敏感词库和替换策略,可以根据实际需求添加、删除或修改敏感词;
  3. 支持对文本中的敏感词进行替换或标记,可以根据实际需求选择合适的处理方式;
  4. 支持对敏感词进行分组,可以根据实际需求对敏感词进行分类管理。

总之,sensitive-word 工具包是一个功能强大、易于使用的敏感词过滤工具,可以帮助开发者快速、准确地对文本中的敏感词进行过滤,保护用户的隐私和安全。

除了上述功能,sensitive-word 工具包还有以下特点:

  1. 高性能:采用多种优化方式,如位图压缩、缓存预热等,可以提高敏感词匹配速度;
  2. 易于扩展:支持自定义敏感词库和替换策略,可以根据实际需求进行扩展;
  3. 易于集成:可以通过 Maven 或 Gradle 等构建工具进行集成,也可以直接下载源码进行使用;
  4. 开源免费:使用 Apache License 2.0 开源许可证,可以免费商用。

总之,sensitive-word 工具包是一个功能强大、性能高效、易于扩展和集成的敏感词过滤工具,适用于各种 Java 项目,可以帮助开发者提高开发效率和用户体验,减少不良信息的传播。

除了 Java 版本的 sensitive-word 工具包,houbb 大神还开发了其他语言版本的敏感词过滤工具,如 Python 版本的 sensitive 和 Go 版本的 sensitive-go。这些工具包都具有高性能、易于扩展和集成、开源免费等特点,可以根据实际需求选择合适的版本进行使用。 此外,敏感词过滤是一个复杂而重要的问题,需要综合考虑多个因素,如匹配算法、敏感词库、替换策略、性能优化等。因此,在使用敏感词过滤工具时,需要根据实际需求进行调整和优化,以达到最佳的效果和性能。

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

2.配置类

@Configuration
public class SensitiveConfig {

    // 配置默认敏感词 + 自定义敏感词
    IWordDeny wordDeny = WordDenys.chains(WordDenys.system(), new MyWordDeny());
    // 配置默认非敏感词 + 自定义非敏感词
    IWordAllow wordAllow = WordAllows.chains(WordAllows.system(), new MyWordAllow());

    @Bean
    public SensitiveWordBs sensitiveWordBs() {
        return SensitiveWordBs.newInstance()
                // 忽略大小写
                .ignoreCase(true)
                // 忽略半角圆角
                .ignoreWidth(true)
                // 忽略数字的写法
                .ignoreNumStyle(true)
                // 忽略中文的书写格式:简繁体
                .ignoreChineseStyle(true)
                // 忽略英文的书写格式
                .ignoreEnglishStyle(true)
                // 忽略重复词
                .ignoreRepeat(false)
                // 是否启用数字检测
                .enableNumCheck(true)
                // 是否启用邮箱检测
                .enableEmailCheck(true)
                // 是否启用链接检测
                .enableUrlCheck(true)
                // 数字检测,自定义指定长度
                .numCheckLen(8)
                // 配置自定义敏感词
                .wordDeny(wordDeny)
                // 配置非自定义敏感词
                .wordAllow(wordAllow)
                .init();
    }

}

3.自定义

public class MySensitiveWordReplace implements ISensitiveWordReplace {
    @Override
    public String replace(ISensitiveWordReplaceContext context) {
        String sensitiveWord = context.sensitiveWord();
        // 自定义不同的敏感词替换策略,可以从数据库等地方读取
        if ("五星红旗".equals(sensitiveWord)) {
            return "国家旗帜";
        }
        if ("毛主席".equals(sensitiveWord)) {
            return "教员";
        }
        // 其他默认使用 * 代替
        int wordLength = context.wordLength();
        return CharUtil.repeat('*', wordLength);
    }
}
@Slf4j
public class MyWordAllow implements IWordAllow {

    @Override
    public List<String> allow() {
        List<String> list = new ArrayList<>();
        ;
        try {
            Resource myAllowWords = new ClassPathResource("myNotSensitiveWords.txt");
            Path myAllowWordsPath = Paths.get(myAllowWords.getFile().getPath());
            list = Files.readAllLines(myAllowWordsPath, StandardCharsets.UTF_8);
        } catch (IOException ioException) {
            log.error("读取非敏感词文件错误!" + ioException.getMessage());
        }
        return list;
    }

}
@Slf4j
public class MyWordDeny implements IWordDeny {

    @Override
    public List<String> deny() {
        List<String> list = new ArrayList<>();
        try {
            Resource mySensitiveWords = new ClassPathResource("mySensitiveWords.txt");
            Path mySensitiveWordsPath = Paths.get(mySensitiveWords.getFile().getPath());
            list = Files.readAllLines(mySensitiveWordsPath, StandardCharsets.UTF_8);
        } catch (IOException ioException) {
            log.error("读取敏感词文件错误!" + ioException.getMessage());
        }
        return list;
    }

}

4.在 resources 下添加文件

文件以及文件内容如下

非敏感: myNotSensitiveWords.txt

小码哥

敏感: mySensitiveWords.txt

国家
马化腾

5.工具类

@Component
public class SensitiveWordUtil {

    @Autowired
    private SensitiveWordBs sensitiveWordBs;

    // 刷新敏感词库与非敏感词库缓存
    public void refresh() {
        sensitiveWordBs.init();
    }

    // 判断是否含有敏感词
    public boolean contains(String text) {
        return sensitiveWordBs.contains(text);
    }

    // 指定替换符进行替换敏感词
    public String replace(String text, char replaceChar) {
        return sensitiveWordBs.replace(text, replaceChar);
    }

    // 使用默认替换符 * 进行替换敏感词
    public String replace(String text) {
        return sensitiveWordBs.replace(text);
    }

    // 返回所有敏感词
    public List<String> findAll(String text) {
        return sensitiveWordBs.findAll(text);
    }
}

6.测试

import com.kwan.springbootkwan.utils.SensitiveWordUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = SpringBootKwanApplication.class)
public class SensitiveTest {

    @Autowired
    private SensitiveWordUtil sensitiveWordUtil;

    @Test
    public void test() {
        String result = sensitiveWordUtil.replace("国家 哇 nnd 复活 马化腾");
        System.out.println(result);
    }
}

7.结果

image-20230324152958533

❤️❤️❤️本人水平有限,如有纰漏,欢迎各位大佬评论批评指正!😄😄😄

💘💘💘如果觉得这篇文对你有帮助的话,也请给个点赞、收藏下吧,非常感谢!👍 👍 👍

🔥🔥🔥Stay Hungry Stay Foolish 道阻且长,行则将至,让我们一起加油吧!🌙🌙🌙
img