houbb / sensitive-word

👮‍♂️The sensitive word tool for java.(敏感词/违禁词/违法词/脏词。基于 DFA 算法实现的高性能 java 敏感词过滤工具框架。请勿发布涉及政治、广告、营销、翻墙、违反国家法律法规等内容。高性能敏感词检测过滤组件,附带繁体简体互换,支持全角半角互换,汉字转拼音,模糊搜索等功能。)
https://houbb.github.io/opensource/sensitive-word
Apache License 2.0
4.1k stars 545 forks source link

SensitiveWordBs#replace如何实现可以切换的自定义替换策略 #71

Closed hu1045274719 closed 2 weeks ago

hu1045274719 commented 1 month ago

在文档中自定义替换策略的例子使用的是SensitiveWordHelper.replace(text, replace);

我想用SensitiveWordBs做自定义替换,能灵活切换替换策略,但是SensitiveWordBs只有一个replace(String target)方法,请问应该如何实现可以切换策略的自定义替换?

比如字符串 "ABCDEFG" 使用A替换策略替换成 "ABCDaaa", 字符串 "1234567" 使用B替换策略替换成 "1234***"

houbb commented 1 month ago

自定义替换策略,文档中有的,直接搜索一下。可以自定义

发自我的iPhone

------------------ 原始邮件 ------------------ 发件人: humomo @.> 发送时间: 2024年8月7日 23:51 收件人: houbb/sensitive-word @.> 抄送: Subscribed @.***> 主题: Re: [houbb/sensitive-word] SensitiveWordBs#replace如何实现可以切换的自定义替换策略 (Issue #71)

在文档中自定义替换策略的例子使用的是SensitiveWordHelper.replace(text, replace);

我想用SensitiveWordBs做自定义替换,能灵活切换替换策略,但是SensitiveWordBs只有一个replace(String target)方法,请问应该如何实现可以切换策略的自定义替换?

比如字符串 "ABCDEFG" 使用A替换策略替换成 "ABCDaaa", 字符串 "1234567" 使用B替换策略替换成 "1234***"

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you are subscribed to this thread.Message ID: @.***>

houbb commented 2 weeks ago
final String text = "五星红旗迎风飘扬,毛主席的画像屹立在天安门前。";

        IWordReplace replace = new MyWordReplace();
        String result = SensitiveWordHelper.replace(text, replace);

        Assert.assertEquals("国家旗帜迎风飘扬,教员的画像屹立在***前。", result);

自定义实现例子:

package com.github.houbb.sensitive.word.replace;

import com.github.houbb.sensitive.word.api.IWordReplace;
import com.github.houbb.sensitive.word.api.IWordContext;
import com.github.houbb.sensitive.word.api.IWordResult;
import com.github.houbb.sensitive.word.utils.InnerWordCharUtils;

/**
 * 自定义敏感词替换策略
 *
 * @author binbin.hou
 * @since 0.2.0
 */
public class MyWordReplace implements IWordReplace {

    @Override
    public void replace(StringBuilder stringBuilder, final char[] rawChars, IWordResult wordResult, IWordContext wordContext) {
        String sensitiveWord = InnerWordCharUtils.getString(rawChars, wordResult);
        // 自定义不同的敏感词替换策略,可以从数据库等地方读取
        if("五星红旗".equals(sensitiveWord)) {
            stringBuilder.append("国家旗帜");
        } else if("毛主席".equals(sensitiveWord)) {
            stringBuilder.append("教员");
        } else {
            // 其他默认使用 * 代替
            int wordLength = wordResult.endIndex() - wordResult.startIndex();
            for(int i = 0; i < wordLength; i++) {
                stringBuilder.append('*');
            }
        }
    }

}