1. 程式人生 > >Java 敏感詞替換-dfa演算法,效率高

Java 敏感詞替換-dfa演算法,效率高

實現的步驟:1.用一個方法來讀取敏感詞放入一個List集合

                      2.寫一個敏感詞庫方法讀取集合中的敏感詞,然後生成樹形結構,

                      3.寫一個查詢傳入字串查詢其中的敏感詞的方法,找到字串中的敏感詞

                      4.替換敏感詞

寫一個工具類,包含讀取敏感詞,生成敏感詞庫,檢查字串中的敏感詞幾個方法

package com.utils.dfa;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import 
java.io.InputStreamReader; import java.util.*; /** * @Description: 初始化敏感詞庫,將敏感詞加入到HashMap中,構建DFA演算法模型 * @Project:test * @Author : SPF * @version 1.0 */ public class SensitiveWordInit { private String ENCODING = "UTF-8"; //字元編碼 @SuppressWarnings("rawtypes") public static HashMap sensitiveWordMap
; public SensitiveWordInit(){ super(); } /** * 初始化詞庫 * @param datas 敏感詞集合 * @return */ public static HashMap init(List<String> datas) { addSensitiveWord(datas); return sensitiveWordMap; } /** * 讀取敏感詞庫,將敏感詞放入HashSet中,構建一個DFA演算法模型:<br> * 中 = {
* isEnd = 0 * 國 = {<br> * isEnd = 1 * 人 = {isEnd = 0 * 民 = {isEnd = 1} * } * 男 = { * isEnd = 0 * 人 = { * isEnd = 1 * } * } * } * } * 五 = { * isEnd = 0 * 星 = { * isEnd = 0 * 紅 = { * isEnd = 0 * 旗 = { * isEnd = 1 * } * } * } * } * {退={黨={isEnd=1}, isEnd=0}, 老={isEnd=0, 虎={機={上={分={器={isEnd=1}, isEnd=0}, isEnd=0}, isEnd=1}, isEnd=0}} */ private static void addSensitiveWord(List<String> datas) { sensitiveWordMap = new HashMap(datas.size()); Iterator<String> iterator = datas.iterator(); Map<String, Object> now = null; Map now2 = null; while (iterator.hasNext()) { now2 = sensitiveWordMap; String word = iterator.next().trim(); //敏感詞 for (int i = 0; i < word.length(); i++) { char key_word = word.charAt(i); Object obj = now2.get(key_word); if (obj != null) { //存在 now2 = (Map) obj; } else { //不存在 now = new HashMap<String, Object>(); now.put("isEnd","0"); now2.put(key_word, now); now2 = now; } if (i == word.length() - 1) { now2.put("isEnd","1"); } } } } /** * 獲取內容中的敏感詞 * @param text 內容 * @param matchType 匹配規則 1=不最佳匹配,2=最佳匹配 * @return */ public static List<String> getSensitiveWord(String text, int matchType) { List<String> words = new ArrayList<String>(); Map now = sensitiveWordMap; int count = 0; //初始化敏感詞長度 int start = 0; //標誌敏感詞開始的下標 for (int i = 0; i < text.length(); i++) { char key = text.charAt(i); now = (Map) now.get(key); if (now != null) { //存在 count++; if (count ==1) { start = i; } if ("1".equals(now.get("isEnd"))) { //敏感詞結束 now = sensitiveWordMap; //重新獲取敏感詞庫 words.add(text.substring(start, start + count)); //取出敏感詞,新增到集合 count = 0; //初始化敏感詞長度 } } else { //不存在 now = sensitiveWordMap;//重新獲取敏感詞庫 if (count == 1 && matchType == 1) { //不最佳匹配 count = 0; } else if (count == 1 && matchType == 2) { //最佳匹配 words.add(text.substring(start, start + count)); count = 0; } } } return words; } /** * 從檔案中讀取敏感詞庫中的內容,將內容新增到set集合中 * @author chenming * @date 2014年4月20日 下午2:31:18 * @return * @version 1.0 * @throws Exception */ @SuppressWarnings("resource") private Set<String> readSensitiveWordFile() throws Exception{ Set<String> set = null; File file = new File("F:\\SPF\\專案\\敏感詞過濾\\敏感詞彙\\敏感詞庫\\敏感詞2\\SensitiveWord.txt"); //讀取檔案 InputStreamReader read = new InputStreamReader(new FileInputStream(file),ENCODING); try { if(file.isFile() && file.exists()){ //檔案流是否存在 set = new HashSet<String>(); BufferedReader bufferedReader = new BufferedReader(read); String txt = null; while((txt = bufferedReader.readLine()) != null){ //讀取檔案,將檔案內容放入到set中 set.add(txt); } } else{ //不存在丟擲異常資訊 throw new Exception("敏感詞庫檔案不存在"); } } catch (Exception e) { throw e; }finally{ read.close(); //關閉檔案流 } return set; } }

寫個一個提供給介面的替換銘感詞的方法類

package com.utils.dfa;

import java.util.*;

/**
 * @Description: 敏感詞過濾
 * @Project:test
* @version 1.0
 */
public class SensitivewordFilter {
   @SuppressWarnings("rawtypes")
   private static Map sensitiveWordMap = null;
   public static int minMatchTYpe = 1;      //最小匹配規則
public static int maxMatchType = 2;      //最大匹配規則
private static void initSensitiveWord(List<String> datas) {
      sensitiveWordMap = SensitiveWordInit.init(datas);
   }

   /**
    * 替換敏感字字元
    * @author chenming
    * @date 2014年4月20日 下午5:12:07
    * @param txt
* @param matchType
* @param replaceChar 替換字元,預設*
    * @version 1.0
    */
public static String replaceSensitiveWord(List<String> datas, String txt,int matchType,String replaceChar){
      if (sensitiveWordMap == null) {
         initSensitiveWord(datas);
      }
      String resultTxt = txt;
      List<String> set = SensitiveWordInit.getSensitiveWord(txt, matchType);     //獲取所有的敏感詞
System.out.println(set);
      Iterator<String> iterator = set.iterator();
      String word = null;
      String replaceString = null;
      while (iterator.hasNext()) {
         word = iterator.next();
         replaceString = getReplaceChars(replaceChar, word.length());
         resultTxt = resultTxt.replaceAll(word, replaceString);
      }
      return resultTxt;
   }

   /**
    * 獲取替換字串
    * @author chenming
    * @date 2014年4月20日 下午5:21:19
    * @param replaceChar
* @param length    * @return
* @version 1.0
    */
private static String getReplaceChars(String replaceChar,int length){
      String resultReplace = replaceChar;
      if (length > 6) {
         length = 6;
      }
      for(int i = 1 ; i < length ; i++){
         resultReplace += replaceChar;
      }
      return resultReplace;
   }


   /**
    * 新增敏感詞
    * @param str
*/
private static boolean addSensitiveWord(String str) {
      if (sensitiveWordMap == null) {
         return false;
      }
      Map nowMap = null;
      Map<String, String> newWorMap = null;
         nowMap = sensitiveWordMap;
         for(int i = 0 ; i < str.length() ; i++){
            char keyChar = str.charAt(i);       //轉換成char型
Object wordMap = nowMap.get(keyChar);       //獲取
if(wordMap != null){        //如果存在該key,直接賦值
nowMap = (Map) wordMap;
            }
            else{     //不存在則,則構建一個map,同時將isEnd設定為0,因為他不是最後一個
newWorMap = new HashMap<String,String>();
               newWorMap.put("isEnd", "0");     //不是最後一個
nowMap.put(keyChar, newWorMap);
               nowMap = newWorMap;
            }
            if(i == str.length() - 1){
               nowMap.put("isEnd", "1");    //最後一個
}
         }
         return  true;
   }

   public static void main(String[] args) {
      List<String> datas = new ArrayList<String>();
        datas.add("滾");datas.add("臥槽");datas.add("你麻痺");datas.add("去你麻痺");
        datas.add("臥去");datas.add("臥去U");
        initSensitiveWord(datas);
        addSensitiveWord("MDZZQUN");
        String str = "臥去,尼瑪,臥槽牛黃弩機滾,你麻痺你能見MDZZQUN到健康去你麻痺";
      String rep =  replaceSensitiveWord(datas,str,1,"*");
      System.out.println(rep);
   }
}