网站敏感词过滤的实现(附敏感词库)

 

现在基本上所有的网站都需要设置敏感词过滤,似乎已经成了一个网站的标配,如果你的网站没有,或者你没有做相应的处理,那么小心相关部门请你喝茶哦。 
最近在调研Java web网站的敏感词过滤的实现,网上找了相关资料,经过我的验证,把我的调研结果写出来,供大家参考。

一、敏感词过滤工具类

把敏感词词库内容加载到ArrayList集合中,通过双层循环,查找与敏感词列表相匹配的字符串,如果找到以*号替换,最终得到替换后的字符串。

此种方式匹配度较高,匹配速度良好。

初始化敏感词库

 
  1. //初始化敏感词库

  2. public void InitializationWork()

  3. {

  4. replaceAll = new StringBuilder(replceSize);

  5. for(int x=0;x < replceSize;x++)

  6. {

  7. replaceAll.append(replceStr);

  8. }

  9. //加载词库

  10. arrayList = new ArrayList();

  11. InputStreamReader read = null;

  12. BufferedReader bufferedReader = null;

  13. try {

  14. read = new InputStreamReader(SensitiveWord.class.getClassLoader().getResourceAsStream(fileName),encoding);

  15. bufferedReader = new BufferedReader(read);

  16. for(String txt = null;(txt = bufferedReader.readLine()) != null;){

  17. if(!arrayList.contains(txt))

  18. arrayList.add(txt);

  19. }

  20. } catch (UnsupportedEncodingException e) {

  21. e.printStackTrace();

  22. } catch (IOException e) {

  23. e.printStackTrace();

  24. }finally{

  25. try {

  26. if(null != bufferedReader)

  27. bufferedReader.close();

  28. } catch (IOException e) {

  29. e.printStackTrace();

  30. }

  31. try {

  32. if(null != read)

  33. read.close();

  34. } catch (IOException e) {

  35. e.printStackTrace();

  36. }

  37. }

  38. }

过滤敏感词信息

 
  1. public String filterInfo(String str)

  2. {

  3. sensitiveWordSet = new HashSet();

  4. sensitiveWordList= new ArrayList<>();

  5. StringBuilder buffer = new StringBuilder(str);

  6. HashMap hash = new HashMap(arrayList.size());

  7. String temp;

  8. for(int x = 0; x < arrayList.size();x++)

  9. {

  10. temp = arrayList.get(x);

  11. int findIndexSize = 0;

  12. for(int start = -1;(start=buffer.indexOf(temp,findIndexSize)) > -1;)

  13. {

  14. //System.out.println("###replace="+temp);

  15. findIndexSize = start+temp.length();//从已找到的后面开始找

  16. Integer mapStart = hash.get(start);//起始位置

  17. if(mapStart == null || (mapStart != null && findIndexSize > mapStart))//满足1个,即可更新map

  18. {

  19. hash.put(start, findIndexSize);

  20. //System.out.println("###敏感词:"+buffer.substring(start, findIndexSize));

  21. }

  22. }

  23. }

  24. Collection values = hash.keySet();

  25. for(Integer startIndex : values)

  26. {

  27. Integer endIndex = hash.get(startIndex);

  28. //获取敏感词,并加入列表,用来统计数量

  29. String sensitive = buffer.substring(startIndex, endIndex);

  30. //System.out.println("###敏感词:"+sensitive);

  31. if (!sensitive.contains("*")) {//添加敏感词到集合

  32. sensitiveWordSet.add(sensitive);

  33. sensitiveWordList.add(sensitive);

  34. }

  35. buffer.replace(startIndex, endIndex, replaceAll.substring(0,endIndex-startIndex));

  36. }

  37. hash.clear();

  38. return buffer.toString();

  39. }

下载地址:SensitiveWord 
链接: https://pan.baidu.com/s/12RcZ8-jNHMAR__VscRUDfQ 密码: qmcw

二、Java关键词过滤

这个方式采用的是正则表达式匹配,速度上比第一种稍慢,匹配度良好。

主要代码:

 
  1. // 从words.properties初始化正则表达式字符串

  2. private static void initPattern() {

  3. StringBuffer patternBuffer = new StringBuffer();

  4. try {

  5. //words.properties

  6. InputStream in = KeyWordFilter.class.getClassLoader().getResourceAsStream("keywords.properties");

  7. Properties property = new Properties();

  8. property.load(in);

  9. Enumeration enu = property.propertyNames();

  10. patternBuffer.append("(");

  11. while (enu.hasMoreElements()) {

  12. String scontent = (String) enu.nextElement();

  13. patternBuffer.append(scontent + "|");

  14. //System.out.println(scontent);

  15. keywordsCount ++;

  16. }

  17. patternBuffer.deleteCharAt(patternBuffer.length() - 1);

  18. patternBuffer.append(")");

  19. //System.out.println(patternBuffer);

  20. // unix换成UTF-8

  21. // pattern = Pattern.compile(new

  22. // String(patternBuf.toString().getBytes("ISO-8859-1"), "UTF-8"));

  23. // win下换成gb2312

  24. // pattern = Pattern.compile(new String(patternBuf.toString()

  25. // .getBytes("ISO-8859-1"), "gb2312"));

  26. // 装换编码

  27. pattern = Pattern.compile(patternBuffer.toString());

  28. } catch (IOException ioEx) {

  29. ioEx.printStackTrace();

  30. }

  31. }

  32.  
  33. private static String doFilter(String str) {

  34. Matcher m = pattern.matcher(str);

  35. // while (m.find()) {// 查找符合pattern的字符串

  36. // System.out.println("The result is here :" + m.group());

  37. // }

  38. // 选择替换方式,这里以* 号代替

  39. str = m.replaceAll("*");

  40. return str;

  41. }

下载地址:KeyWordFilter 
链接: http://pan.baidu.com/s/1kVBl803 密码: xi24

三、DFA算法进行过滤

这种方式听起来高大上,采用DFA算法,这个算法个人不太懂,经测试发现,匹配度不行,速度良好。或许可以改良,还请大神进行改良。

主要有两个文件:SensitivewordFilter.java 和 SensitiveWordInit.java

主要代码:

 
  1. public int CheckSensitiveWord(String txt,int beginIndex,int matchType){

  2. boolean flag = false; //敏感词结束标识位:用于敏感词只有1位的情况

  3. int matchFlag = 0; //匹配标识数默认为0

  4. char word = 0;

  5. Map nowMap = sensitiveWordMap;

  6. for(int i = beginIndex; i < txt.length() ; i++){

  7. word = txt.charAt(i);

  8. nowMap = (Map) nowMap.get(word); //获取指定key

  9. if(nowMap != null){ //存在,则判断是否为最后一个

  10. matchFlag++; //找到相应key,匹配标识+1

  11. if("1".equals(nowMap.get("isEnd"))){ //如果为最后一个匹配规则,结束循环,返回匹配标识数

  12. flag = true; //结束标志位为true

  13. if(SensitivewordFilter.minMatchTYpe == matchType){ //最小规则,直接返回,最大规则还需继续查找

  14. break;

  15. }

  16. }

  17. }

  18. else{ //不存在,直接返回

  19. break;

  20. }

  21. }

  22. if(matchFlag < 2 || !flag){ //长度必须大于等于1,为词

  23. matchFlag = 0;

  24. }

  25. return matchFlag;

  26. }

  • 下载地址:SensitivewordFilter 
    链接: http://pan.baidu.com/s/1ccsa66 密码: mc1x

四、多叉树查找算法

这个方式采用了多叉树查找算法,至于这个算法是怎么回事,大家可以去查看数据结构相关内容。提供了jar包,直接调用进行过滤。

经测试,这个方法匹配度良好,速度稍慢。

调用方式:

 
  1. //敏感词过滤

  2. FilteredResult result = WordFilterUtil.filterText(str, '*');

  3. //获取过滤后的内容

  4. System.out.println("替换后的字符串为:\n"+result.getFilteredContent());

  5. //获取原始字符串

  6. System.out.println("原始字符串为:\n"+result.getOriginalContent());

  7. //获取替换的敏感词

  8. System.out.println("替换的敏感词为:\n"+result.getBadWords());

下载地址:WordFilterUtil 
链接: http://pan.baidu.com/s/1nvftzeD 密码: 5t2h

以上就是我的调研结果,希望对大家有所帮助。

最后,附上大量敏感词库下载地址: 
链接: https://pan.baidu.com/s/1n-GH-OO6nQ5oJk5h5qHVkA 密码: qsv9

你可能感兴趣的:(网站敏感词过滤的实现(附敏感词库))