项目目录结构
代码
创建一个名为SensitiveWordFilter的Java类:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class SensitiveWordFilter {
private Set<String> sensitiveWords;
public SensitiveWordFilter(String filePath) {
sensitiveWords = new HashSet<>();
loadSensitiveWords(filePath);
}
private void loadSensitiveWords(String filePath) {
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
sensitiveWords.add(line.trim());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String filter(String text) {
for (String word : sensitiveWords) {
//用“***”代替敏感词
text = text.replaceAll(word, "***");
}
return text;
}
public static void main(String[] args) {
//敏感词文件的路径
SensitiveWordFilter filter = new SensitiveWordFilter("src\\sensitive_words.txt");
//要进行过滤的文本
String text = "这是一个敏感词过滤系统,包含敏感词如:色情、暴力、赌博等";
String filteredText = filter.filter(text);
//过滤后输出的文本
System.out.println(filteredText);
}
}
创建一个名为sensitive_words.txt的文本文件,将敏感词逐行写入该文件:
色情
暴力
将SensitiveWordFilter.java和sensitive_words.txt放在同一个目录下,然后编译并运行SensitiveWordFilter.java即可实现敏感词过滤功能。