在github上找到了很好用的api叫ToolGood.Words链接在下边可以参考文档实现
https://github.com/toolgood/ToolGood.Words/tree/master/java/toolgood.words
我开发过程中研究了一下具体步骤大概是这样的
1.导入pom依赖
<dependency>
<groupId>io.github.toolgood</groupId>
<artifactId>toolgood-words</artifactId>
<version>3.0.3.1</version>
</dependency>
它里面有非法词(敏感词)检测类:StringMatch
、WordsMatch
。(我用的是StringMatch,WordsMatch后边后用的时候会报错具体原因下边会说
)
2.在网上找个敏感词词汇(txt文件就行),文件编码一定要是utf8,把它放入resources目录下
我自己总结了一份敏感词汇.txt访问链接下载就行
https://pan.baidu.com/s/1Nkc3ulph-uqm8EaVlUJ8dg
提取码:yyds
3.首先获取到mgc.txt文件路径
String path = Thread.currentThread().getContextClassLoader().getResource("static/mgc.txt").getPath();
之后引用工具类使txt文件内容变成List<String>集合
/**
* 根据文件路径获取到list集合
* @param filePath
* @return
*/
public static List<String> readTxt(String filePath) {
List<String> list = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = br.readLine()) != null) {
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
得到一个list集合,调用api封装的方法(正常步骤)为了方便测试我自定义一个list
这个搜索类还有其他方法
基本上就这两个常用(看个人)Replace是检测字符串中存在敏感词就用特殊符号打码,例如:我叫***。ContainsAny是检测字符串中是否包含敏感词汇返回true或者false。
下边是测试结果:
结果很明了。
回答一下上边提到的另一个WordsMatch类为什么不用,因为我在开发过程中发现当你list长度过长的时候会报错,长度一般的话也能正常使用,WordsMatch类中的方法和StringMatch中的方法一模一样。
当你list过大时会报这种错误:
会出现索引越界问题而StringMatch能正常使用
下边封装好的工具类
public class FileUntil {
/**
* 根据文件路径获取到list集合
* @param filePath
* @return
*/
public static List<String> readTxt(String filePath) {
List<String> list = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = br.readLine()) != null) {
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 判断是否存在敏感词
* @param txt
* @return
*/
public static Boolean judgeSensitivityWord(String txt) {
String path = Thread.currentThread().getContextClassLoader().getResource("static/mgc.txt").getPath();
List<String> list = readTxt(path);
StringSearch iwords = new StringSearch ();
iwords.SetKeywords(list);
return iwords.ContainsAny(txt);
}
/**
* 敏感词过滤用*替代
* @param txt 内容
* @param replace 敏感词替代字符 '*'
* @return
*/
public static String filterSensitivityWord(String txt,char replace){
String path = Thread.currentThread().getContextClassLoader().getResource("static/mgc.txt").getPath();
List<String> list = readTxt(path);
StringSearch iwords = new StringSearch ();
iwords.SetKeywords(list);
return iwords.Replace(txt,replace);
}
}
总结不易,希望大家都能进步。
版权声明:本文为m0_59096111原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。