Java 简单敏感词过滤
Wenhao Wang 2020-08-19 DAF敏感词过滤
Java 实现对敏感词的过滤和替换,基于 DAF 实现
# DFA
算法和 MAP
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* 参考DFA算法
*/
public class BadWordUtil {
/**
* 敏感词库文件路径
*/
public static final String FILE_PATH = "SensitiveWords.txt";
// public static final String FILE_PATH = "test.txt";
/**
* 最小匹配规则
*/
public static final int MIN_MATCH_TYPE = 1;
/**
* 最大匹配规则
*/
public static final int MAX_MATCH_TYPE = 2;
public static Map<String, String> wordDictMap;
static {
// 加载词典,建立 DFA 树
addBadWordToHashMap(readTxtByLine());
}
private static Set<String> readTxtByLine() {
Set<String> keyWordSet = new HashSet<>();
String txt;
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(BadWordUtil.class.getClassLoader().getResourceAsStream(FILE_PATH)), StandardCharsets.UTF_8))) {
while ((txt = bufferedReader.readLine()) != null) {
keyWordSet.add(txt);
}
} catch (IOException e) {
e.printStackTrace();
}
return keyWordSet;
}
/**
* 检查文字中是否包含敏感字符,检查规则如下:<br>
*
* @param txt 文本
* @param beginIndex 开始索引
* @param matchType 匹配规则
* @return 如果存在,则返回敏感词字符的长度,不存在返回0
*/
@SuppressWarnings({"rawtypes"})
public static int checkBadWord(String txt, int beginIndex, int matchType) {
// 敏感词结束标识位:用于敏感词未完全匹配的情况
boolean flag = false;
// 匹配标识数默认为0
int matchLength = 0;
char word;
Map currentMap = wordDictMap;
for (int i = beginIndex; i < txt.length(); i++) {
word = txt.charAt(i);
// 获取指定key
currentMap = (Map) currentMap.get(word);
// 存在,则判断是否为最后一个
if (currentMap != null) {
// 找到相应key,匹配标识+1
matchLength++;
// 如果为最后一个匹配规则,结束循环,返回匹配标识数
if ("1".equals(currentMap.get("isEnd"))) {
// 结束标志位为true
flag = true;
// 最小规则,直接返回,最大规则还需继续查找
if (MIN_MATCH_TYPE == matchType) {
break;
}
}
} else {
// 不存在,直接返回
break;
}
}
if (!flag) {
matchLength = 0;
}
return matchLength;
}
/**
* 判断文字是否包含敏感字符
*
* @param txt 文字
* @param matchType 匹配规则 1:最小匹配规则,2:最大匹配规则
* @return 若包含返回true,否则返回false
*/
public static boolean isContainBadWord(String txt, int matchType) {
boolean flag = false;
for (int i = 0; i < txt.length(); i++) {
// 判断是否包含敏感字符
int matchFlag = checkBadWord(txt, i, matchType);
// 大于0存在,返回true
if (matchFlag > 0) {
flag = true;
}
}
return flag;
}
/**
* 替换敏感字字符
*
* @param txt 文本
* @param matchType 匹配规则
*/
public static String replaceBadWord(String txt, int matchType) {
String resultTxt = txt;
// 获取所有的敏感词
Set<String> set = getBadWord(txt, matchType);
Iterator<String> iterator = set.iterator();
String word;
String replaceString;
while (iterator.hasNext()) {
word = iterator.next();
replaceString = getReplaceChars(word.length());
resultTxt = resultTxt.replaceAll(word, replaceString);
}
return resultTxt;
}
/**
* 获取文字中的敏感词
*
* @param txt 文字
* @param matchType 匹配规则 1:最小匹配规则,2:最大匹配规则
*/
public static Set<String> getBadWord(String txt, int matchType) {
Set<String> sensitiveWordList = new HashSet<>();
for (int i = 0; i < txt.length(); i++) {
// 判断是否包含敏感字符
int length = checkBadWord(txt, i, matchType);
// 存在,加入list中
if (length > 0) {
sensitiveWordList.add(txt.substring(i, i + length));
// 减1的原因,是因为for会自增
i = i + length - 1;
}
}
return sensitiveWordList;
}
/**
* 获取等长替换字符串
*/
private static String getReplaceChars(int length) {
StringBuilder resultReplace = new StringBuilder();
for (int i = 0; i < length; i++) {
resultReplace.append("*");
}
return resultReplace.toString();
}
/**
* 将我们的敏感词库构建成了一个类似与一颗一颗的树,这样我们判断一个词是否为敏感词时就大大减少了检索的匹配范围。
*
* @param keyWordSet 敏感词库
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private static void addBadWordToHashMap(Set<String> keyWordSet) {
// 初始化敏感词容器,减少扩容操作
wordDictMap = new HashMap(keyWordSet.size());
Map currentMap;
Map<String, String> newWordMap;
// 迭代keyWordSet
for (String key : keyWordSet) {
// 关键字
currentMap = wordDictMap;
for (int i = 0; i < key.length(); i++) {
// 转换成char型
char keyChar = key.charAt(i);
// 获取
Object charMap = currentMap.get(keyChar);
// 如果存在该key,直接赋值
if (charMap != null) {
currentMap = (Map) charMap;
} else {
// 不存在则构建一个map,同时将isEnd设置为0,因为他不是最后一个
newWordMap = new HashMap<>(16);
// 不是最后一个
newWordMap.put("isEnd", "0");
currentMap.put(keyChar, newWordMap);
currentMap = newWordMap;
}
if (i == key.length() - 1) {
// 最后一个
currentMap.put("isEnd", "1");
}
}
}
}
public static void main(String[] args) throws IOException {
System.out.println("敏感词的数量:" + BadWordUtil.wordDictMap.size());
String text = "日本太多的伤感情怀也许只局限于饲养基地 荧幕中的情节,主人公尝试着去用某种方式渐渐的很潇洒地释自杀指南怀那些自己经历的伤感。"
+ "然后法轮功 我们的扮演的角色日本人鬼子就是跟随着主人公的喜红客联盟 怒哀乐而过于牵强的把自己的情感也附加于银幕情节中,然后感动就流泪,"
+ "难过就躺在某一个人的怀里尽情的阐述心扉或者手机卡操你妈复制器一个人一杯红酒一部电影在夜三级片 深人静的晚上,关上电话静静的发呆着。";
StringBuilder sb = new StringBuilder(text);
for (int i = 0; i < 10000; i++) {
sb.append(text);
}
text = sb.toString();
System.out.println("待检测语句字数:" + text.length());
long beginTime = System.currentTimeMillis();
Set<String> set = BadWordUtil.getBadWord(text, MAX_MATCH_TYPE);
System.out.println("语句中包含敏感词的个数为:" + set.size() + "。包含:" + set);
System.out.println(BadWordUtil.replaceBadWord(text, MAX_MATCH_TYPE));
long endTime = System.currentTimeMillis();
System.out.println("总共消耗时间为:" + (endTime - beginTime));
// BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("D:\\test\\11111.txt"));
// Set<String> strings = BadWordUtil.readTxtByLine(filePath);
// for (String string : strings) {
// bufferedWriter.write(string);
// bufferedWriter.newLine();
// }
// bufferedWriter.flush();
// bufferedWriter.close();
}
}
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
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