关于过滤敏感词,返回这个string中的敏感词,利用hutool来实现。敏感词写在一个txt文件中。

首先导入hutool的依赖

然后需要写一个NLPUtil工具类。

工具类代码:

public class NLPUtil {

    // 敏感词、违禁词 Map
    private static final WordTree BADWORDS_TREE = new WordTree();

    /**
     * 加载敏感词、违禁词
     */
    public static void loadBadwords() throws IOException {
        String path = "badwords.dic";
        ClassPathResource resource = new ClassPathResource(path);
        InputStream inputStream = resource.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        while((line = br.readLine())!=null) {
            BADWORDS_TREE.addWord(line.trim());
        }
        br.close();
    }

    /**
     * 敏感词,违禁词检测
     */
    public static List<String> checkBadwords(String content) {
        if(BADWORDS_TREE.size() == 0) {
            try {
                loadBadwords();
            } catch (IOException e) {
                e.printStackTrace();
                return new ArrayList<>();
            }
        }

        // 匹配到最长关键词,跳过已经匹配的关键词
        String sentence = HtmlUtil.cleanHtmlTag(content);
        List<String> words = BADWORDS_TREE.matchAll(sentence, -1, false, true);

        List<String> newWords = new ArrayList<>();
        // 过滤该词在某个单词里面
        for(String word : words) {
            if(Validator.isWord(word) && !content.contains(" " + word) && !content.contains(word + " ")) {
                continue;
            }
            newWords.add(word);
        }
        return newWords;
    }

}

关于使用,调用该方法就行:

     /**
     * 检测文本的敏感词、违禁词
     */
    public AjaxResult checkBadwords(@RequestBody KsComment ksComment) {
        String content = ksComment.getContent();
        if(StringUtils.isEmpty(content)) {
            return AjaxResult.error("文本内容不能为空");
        }

        List<String> badwordsSet = NLPUtil.checkBadwords(content);
        return AjaxResult.success(badwordsSet);
    }


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值