1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
| import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson2.JSON; import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.regex.Pattern;
@Slf4j public class SensitiveWordUtil {
public static final int MIN_MATCH_TYPE = 1;
public static final int MAX_MATCH_TYPE = 2;
private static volatile Map<Character, SensitiveNode> sensitiveWordMap;
private static final Pattern SPECIAL_CHAR_PATTERN = Pattern.compile("[`~!@#$%^&*()+=|{}:;\\[\\].<>/?~!@#¥%……&*()——+|{}【】';:\"。,、?\\s]");
private static class SensitiveNode { private boolean isEnd; private final Map<Character, SensitiveNode> children;
public SensitiveNode() { this.children = new HashMap<>(); this.isEnd = false; }
public boolean isEnd() { return isEnd; }
public void setEnd(boolean end) { isEnd = end; }
public Map<Character, SensitiveNode> getChildren() { return children; }
public SensitiveNode getChild(Character key) { return children.get(key); }
public SensitiveNode putChild(Character key, SensitiveNode node) { return children.put(key, node); }
public SensitiveNode removeChild(Character key) { return children.remove(key); }
public boolean hasChildren() { return !children.isEmpty(); } }
public static synchronized void load(Set<String> sensitiveWordSet) { if (sensitiveWordSet == null || sensitiveWordSet.isEmpty()) { sensitiveWordMap = Collections.emptyMap(); log.warn("==加载敏感词库: 词库为空=="); return; }
initWords(sensitiveWordSet); log.info("==加载敏感词库完成,共{}个敏感词==", sensitiveWordSet.size()); }
private static void initWords(Set<String> sensitiveWordSet) { Map<Character, SensitiveNode> newWordMap = new HashMap<>(sensitiveWordSet.size());
for (String word : sensitiveWordSet) { if (StrUtil.isNotBlank(word)) { addWord(word, newWordMap); } }
sensitiveWordMap = newWordMap; }
public static void addWord(String word, Map<Character, SensitiveNode> wordMap) { if (StrUtil.isBlank(word)) { return; } Map<Character, SensitiveNode> currentMap = wordMap;
for (int i = 0; i < word.length(); i++) { char keyChar = word.charAt(i); SensitiveNode node = currentMap.get(keyChar);
if (node == null) { node = new SensitiveNode(); currentMap.put(keyChar, node); }
if (i == word.length() - 1) { node.setEnd(true); } currentMap = node.getChildren(); } }
public static boolean removeWord(String word) { return removeWord(word, sensitiveWordMap); }
public static boolean removeWord(String word, Map<Character, SensitiveNode> wordMap) { if (StrUtil.isBlank(word) || wordMap == null) { return false; } return removeWordRecursive(word, 0, wordMap, new ArrayList<>()); }
private static boolean removeWordRecursive(String word, int index, Map<Character, SensitiveNode> currentMap, List<Map<Character, SensitiveNode>> parentMaps) { if (index == word.length()) { return false; }
char currentChar = word.charAt(index); SensitiveNode currentNode = currentMap.get(currentChar);
if (currentNode == null) { return false; }
parentMaps.add(currentMap);
if (index == word.length() - 1) { if (currentNode.isEnd()) { if (!currentNode.hasChildren()) { Map<Character, SensitiveNode> parentMap = parentMaps.get(parentMaps.size() - 1); parentMap.remove(currentChar); } else { currentNode.setEnd(false); } log.info("敏感词库已移除/更新:{} 关键词", word); return true; } return false; }
return removeWordRecursive(word, index + 1, currentNode.getChildren(), parentMaps); }
public static boolean contains(String txt) { return contains(txt, MIN_MATCH_TYPE); }
public static boolean contains(String txt, int matchType) { if (StrUtil.isBlank(txt) || sensitiveWordMap == null || sensitiveWordMap.isEmpty()) { return false; }
String filteredTxt = filterSpecialStr(txt); for (int i = 0; i < filteredTxt.length(); i++) { if (checkWord(filteredTxt, i, matchType) > 0) { return true; } } return false; }
public static Set<String> getSensitiveWord(String txt) { return getSensitiveWord(txt, MIN_MATCH_TYPE); }
public static Set<String> getSensitiveWord(String txt, int matchType) { Set<String> resultSet = new LinkedHashSet<>();
if (StrUtil.isBlank(txt) || sensitiveWordMap == null || sensitiveWordMap.isEmpty()) { return resultSet; }
String filteredTxt = filterSpecialStr(txt); for (int i = 0; i < filteredTxt.length(); i++) { int length = checkWord(filteredTxt, i, matchType); if (length > 0) { resultSet.add(filteredTxt.substring(i, i + length)); i += length - 1; } } return resultSet; }
public static String replaceWordByOne(String txt, String replaceValue) { return replaceWord(txt, replaceValue, MAX_MATCH_TYPE, false); }
public static String replaceWordByAll(String txt, String replaceStr) { return replaceWord(txt, replaceStr, MAX_MATCH_TYPE, true); }
public static String replaceWord(String txt, String replaceValue, int matchType, boolean isReplaceAll) { if (StrUtil.isBlank(txt) || sensitiveWordMap == null || sensitiveWordMap.isEmpty()) { return txt; }
StringBuilder resultBuilder = new StringBuilder(txt); Set<String> sensitiveWords = getSensitiveWord(txt, matchType);
for (String word : sensitiveWords) { String replacement = isReplaceAll ? replaceValue : String.valueOf(replaceValue).repeat(word.length()); int startIndex; while ((startIndex = resultBuilder.indexOf(word)) != -1) { resultBuilder.replace(startIndex, startIndex + word.length(), replacement); } }
return resultBuilder.toString(); }
public static String replaceWordWithFilter(String txt, String replaceValue, int matchType, boolean isReplaceAll) { if (StrUtil.isBlank(txt)) { return txt; }
String filteredTxt = filterSpecialStr(txt); return replaceWord(filteredTxt, replaceValue, matchType, isReplaceAll); }
private static int checkWord(String txt, int beginIndex, int matchType) { if (sensitiveWordMap == null) { return 0; }
int matchFlag = 0; boolean foundEnd = false; Map<Character, SensitiveNode> currentMap = sensitiveWordMap;
for (int i = beginIndex; i < txt.length(); i++) { char currentChar = txt.charAt(i); SensitiveNode node = currentMap.get(currentChar);
if (node == null) { break; }
matchFlag++; if (node.isEnd()) { foundEnd = true; if (matchType == MIN_MATCH_TYPE) { break; } } currentMap = node.getChildren(); }
return foundEnd ? matchFlag : 0; }
public static String filterSpecialStr(String str) { if (StrUtil.isBlank(str)) { return str; } return SPECIAL_CHAR_PATTERN.matcher(str).replaceAll(""); }
public static Set<String> readFile(List<String> filePaths) { Set<String> result = new LinkedHashSet<>();
if (filePaths == null || filePaths.isEmpty()) { return result; }
for (String filePath : filePaths) { readSingleFile(filePath, result); }
return result; }
private static void readSingleFile(String filePath, Set<String> result) { File file = new File(filePath); if (!file.exists() || !file.isFile()) { log.warn("找不到指定的文件: {}", filePath); return; }
int count = 0; try (FileInputStream fis = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(fis, StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader(reader)) {
String line; while ((line = bufferedReader.readLine()) != null) { if (StrUtil.isNotBlank(line)) { String trimmedLine = line.trim(); result.add(trimmedLine); count++; } }
log.info("加载文件:{},成功加载 {} 个敏感词", filePath, count);
} catch (Exception e) { log.error("加载敏感词文件出错: {}", filePath, e); } }
public static int getSensitiveWordCount() { if (sensitiveWordMap == null) { return 0; } return countWords(sensitiveWordMap); }
private static int countWords(Map<Character, SensitiveNode> nodeMap) { int count = 0; for (SensitiveNode node : nodeMap.values()) { if (node.isEnd()) { count++; } count += countWords(node.getChildren()); } return count; }
public static void main(String[] args) { testSensitiveWord(); System.out.println(JSON.toJSONString(sensitiveWordMap)); }
private static void testSensitiveWord() { Set<String> sensitiveWordSet = new HashSet<>(); sensitiveWordSet.add("代开发票"); sensitiveWordSet.add("代购"); sensitiveWordSet.add("代购商"); sensitiveWordSet.add("敏感词");
SensitiveWordUtil.load(sensitiveWordSet);
String content = "结束标志位结束代购商!标职业志位结束#标$敏感%位结束标志代开$发票位代购结束标志位结束苹果标";
System.out.println("原始文本: " + content); System.out.println("过滤后文本: " + filterSpecialStr(content));
boolean isContains = contains(content); Set<String> sensitiveWords = getSensitiveWord(content); System.out.println("文本包含敏感词: " + isContains); System.out.println("发现的敏感词: " + sensitiveWords);
System.out.println("按字符替换: " + replaceWordByOne(content, "*")); System.out.println("按词替换: " + replaceWordByAll(content, "***"));
System.out.println("带过滤的替换: " + replaceWordWithFilter(content, "*", MAX_MATCH_TYPE, false));
System.out.println("当前敏感词数量: " + getSensitiveWordCount()); } }
|