提交订单评价时需要对评价内容进行判断,如果出现敏感词则提示修改
这不就是写一个敏感词的校验工具类吗,小问题,说干就干
读取文件时不需要每次都读取,用一个静态代码块坐初始化,读取完毕后放入jvm缓存
//敏感词库 通过jvm缓存
private static final Set<String> sensitiveWords = new HashSet<>();
static {
//静态代码块加载敏感词库
load("../../../../../../../../resources/file/sensitiveWord.txt");
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* 敏感词工具类
* @author woniu
* 2023-11-09
*/
@Slf4j
public class WordUtil {
//敏感词库 通过jvm缓存
private static final Set<String> sensitiveWords = new HashSet<>();
static {
//静态代码块加载敏感词库
load("../../../../../../../../resources/file/sensitiveWord.txt");
}
/**
* 从敏感文件中逐行读取,加载到敏感词 set中
* @param filePath 文件路径
*/
public static void load(String filePath) {
if (CollectionUtils.isEmpty(sensitiveWords)) {
try (BufferedReader reader = new BufferedReader(new FileReader(filePath));){
String line;
//逐行读取文件
while ((line = reader.readLine()) != null) {
sensitiveWords.add(line);
}
} catch (FileNotFoundException e) {
log.error("读取敏感词库文件错误,文件不存在");
} catch (IOException e) {
log.error("读取敏感词库文件错误,io问题");
}
}
}
/**
* 判断传入文本中是否包含敏感词
* @param word
* @return
*/
public static boolean containsSensitiveWord(String word) {
Iterator<String> iterator = sensitiveWords.iterator();
while (iterator.hasNext()) {
String sensitiveWord = iterator.next();
if (word.contains(sensitiveWord)) {
log.error("匹配到敏感词"+sensitiveWord);
return true;
}
}
return false;
}
public static void main(String[] args) {
boolean aa = containsSensitiveWord("转让");
boolean aa1 = containsSensitiveWord("转让");
boolean aa2 = containsSensitiveWord("转让");
boolean aa3 = containsSensitiveWord("转让");
boolean aa4 = containsSensitiveWord("转让");
}
}
嗯,速度很快,可以下班了
要熟练掌握技巧,一定多多练习:纸上得来终觉浅,绝知此事要躬行。