哎,这文章被我误删了,我都不想再写了。
过滤敏感词:把原文“麻痹,滚远点,你妹的”,替换为“**,滚远点,**的”
最开始我只是简单的替换,但发现并不能这样
敏感词:麻痹麻痹
原文:麻痹麻痹麻痹
那么最后替换:****麻痹
这里面有3个“麻痹麻痹”的排列组合。
package com.ccbft.seecloud.vod.website.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 为道日损
* @version 1.0
* @date 2020/12/22 16:41
* @website https://www.sudo.ren
*/
public class SensitiveTextAlg {
// 递归找到字符所在的位置
private static void getIndexList(List<Integer> list, String text , String word, Integer fromIndex){
int index = text.indexOf(word,fromIndex);
if (index >= 0){
list.add(index);
//int len = word.length();
//fromIndex = index + len;
fromIndex = ++index; //算法优化
getIndexList(list,text,word,fromIndex);
}
}
// 将字符替换为星号
private static String getStars(Integer i){
String stars = "";
for (int j=0;j<i;j++){
stars += "*";
}
return stars;
}
public static String replaceStr(List<String> array, String text) {
// 1.获取敏感词所在的索引位置(可能有多个位置)
Map<String,List<Integer>> wordIndex = new HashMap<>();
for (String word : array) {
List<Integer> list = new ArrayList<>();
getIndexList(list,text,word,0);
wordIndex.put(word, list);
}
// 2.遍历敏感词
for (Map.Entry<String,List<Integer>> entry : wordIndex.entrySet()) {
String word = entry.getKey();
List<Integer> indexList = entry.getValue();
String stars = getStars(word.length());
// 2.1遍历敏感词所在的索引,分割文本,将敏感词用“*”替换。
for (Integer index:indexList){
String start = text.substring(0,index);
String end = text.substring(index + word.length());
text = start + stars + end;
System.out.println(text);
}
System.out.println("==========================");
}
return text;
}
public static void main(String[] args) {
List<String> array = new ArrayList<>();
array.add("草你妈的");
array.add("妈的傻逼");
array.add("你妹");
String text = "草你妈的傻逼草你妈的傻你妹,滚远点逼草你逼草你妈的傻你妹,滚远点妈的傻你妹,滚远点逼草你妈的傻你妹,滚远点";
System.out.println(replaceStr(array,text));
}
}
最后修改于 2020-12-30 02:14:30
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

