天天看點

JAVA 關鍵字、敏感字 屏蔽過濾功能實作

demo目錄結構:

JAVA 關鍵字、敏感字 屏蔽過濾功能實作

文檔内容格式:

JAVA 關鍵字、敏感字 屏蔽過濾功能實作

直接上代碼(檢索敏感詞算法是從網上搜集參考的,有想法的可以搜尋DFA算法研究下):

SensitiveFilterService.java

/**
 * @Author : JCccc
 * @CreateTime : 2019/7/30
 * @Description : 敏感詞過濾器:利用DFA算法  進行敏感詞過濾
 **/

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class SensitiveFilterService {


    private Map sensitiveWordMap = null;

    // 最小比對規則
    public static int minMatchType = 1;

    // 最大比對規則
    public static int maxMatchType = 2;

    // 單例
    private static SensitiveFilterService instance = null;

    // 構造函數,初始化敏感詞庫
    private SensitiveFilterService() {
        sensitiveWordMap = new SensitiveWordInit().initKeyWord();
    }

    // 擷取單例
    public static SensitiveFilterService getInstance() {
        if (null == instance) {
            instance = new SensitiveFilterService();
        }
        return instance;
    }

    // 擷取文字中的敏感詞
    public Set<String> getSensitiveWord(String txt, int matchType) {
        Set<String> sensitiveWordList = new HashSet<String>();
        for (int i = 0; i < txt.length(); i++) {
            // 判斷是否包含敏感字元
            int length = CheckSensitiveWord(txt, i, matchType);
            // 存在,加入list中
            if (length > 0) {
                sensitiveWordList.add(txt.substring(i, i + length));
                // 減1的原因,是因為for會自增
                i = i + length - 1;
            }
        }

        return sensitiveWordList;
    }

    /**
     * 替換敏感字字元
     *
     * @param txt
     * @param matchType
     * @param replaceChar
     * @return
     */
    public String replaceSensitiveWord(String txt, int matchType,
                                       String replaceChar) {
        String resultTxt = txt;
        // 擷取所有的敏感詞
        Set<String> set = getSensitiveWord(txt, matchType);
        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;
    }

    /**
     * 擷取替換字元串
     *
     * @param replaceChar
     * @param length
     * @return
     */
    private String getReplaceChars(String replaceChar, int length) {
        String resultReplace = replaceChar;
        for (int i = 1; i < length; i++) {
            resultReplace += replaceChar;
        }
        return resultReplace;
    }


    /**
     * 檢查文字中是否包含敏感字元,檢查規則如下:<br>
     * 如果存在,則傳回敏感詞字元的長度,不存在傳回0
     *
     * @param txt
     * @param beginIndex
     * @param matchType
     * @return
     */
    public int CheckSensitiveWord(String txt, int beginIndex, int matchType) {

        // 敏感詞結束辨別位:用于敏感詞隻有1位的情況
        boolean flag = false;
        // 比對辨別數預設為0
        int matchFlag = 0;
        Map nowMap = sensitiveWordMap;
        for (int i = beginIndex; i < txt.length(); i++) {
            char word = txt.charAt(i);
            // 擷取指定key
            nowMap = (Map) nowMap.get(word);

            // 存在,則判斷是否為最後一個
            if (nowMap != null) {

                // 找到相應key,比對辨別+1
                matchFlag++;
                // 如果為最後一個比對規則,結束循環,傳回比對辨別數
                if ("1".equals(nowMap.get("isEnd"))) {
                    // 結束标志位為true
                    flag = true;
                    // 最小規則,直接傳回,最大規則還需繼續查找
                    if (SensitiveFilterService.minMatchType == matchType) {
                        break;
                    }
                }
            } else {
                // 不存在,直接傳回
                break;
            }
        }
        if (SensitiveFilterService.maxMatchType == matchType) {
            //長度必須大于等于1,為詞
            if (matchFlag < 2 || !flag) {        
                matchFlag = 0;
            }
        }
        if (SensitiveFilterService.minMatchType == matchType) {
            //長度必須大于等于1,為詞
            if (matchFlag < 2 && !flag) {        
                matchFlag = 0;
            }
        }
        return matchFlag;
    }
}      

SensitiveWordInit.java

package com.example.sensitivedemo.test;

/**
 * @Author : JCccc
 * @CreateTime : 2019/7/30
 * @Description :
 **/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


/**
 * 屏蔽敏感詞初始化
 */
public class SensitiveWordInit {
    // 字元編碼
    private String ENCODING = "UTF-8";
    // 初始化敏感字庫
    public Map initKeyWord() {
        // 讀取敏感詞庫 ,存入Set中
        Set<String> wordSet = readSensitiveWordFile();
        // 将敏感詞庫加入到HashMap中//确定有窮自動機DFA
        return addSensitiveWordToHashMap(wordSet);
    }
    /**
     *      * 讀取敏感詞庫,将敏感詞放入HashSet中,建構一個DFA算法模型:<br> 
     *      * 中 = { 
     *      *      isEnd = 0 
     *      *      國 = { 
     *      *           isEnd = 1 
     *      *           人 = {isEnd = 0 
     *      *                民 = {isEnd = 1} 
     *      *                } 
     *      *           男  = { 
     *      *                  isEnd = 0 
     *      *                   人 = { 
     *      *                        isEnd = 1 
     *      *                       } 
     *      *               } 
     *      *           } 
     *      *      } 
     *      *  五 = { 
     *      *      isEnd = 0 
     *      *      星 = { 
     *      *          isEnd = 0 
     *      *          紅 = { 
     *      *              isEnd = 0 
     *      *              旗 = { 
     *      *                   isEnd = 1 
     *      *                  } 
     *      *              } 
     *      *          } 
     *      *      } 
     *      * @author 孫創    感謝作者
     *      * @date 2017年2月15日 下午3:20:20 
     *      * @param keyWordSet  敏感詞庫 
     *      
     */
    /**
     * 讀取敏感詞庫 ,存入HashMap中
     * @return
     */
    private Set<String> readSensitiveWordFile() {
        Set<String> wordSet = null;
        // app為項目位址
        /*
         * String app = System.getProperty("user.dir"); System.out.println(app);
         * URL resource = Thread.currentThread().getContextClassLoader()
         * .getResource("/"); String path = resource.getPath().substring(1);
         * System.out.println(path); File file = new File(path +
         * "censorwords.txt");
         */


        //敏感詞庫
        File file = new File(
                "E:\\sensitivedemo\\src\\main\\resources\\static\\censorwords.txt");
        try {
            // 讀取檔案輸入流
            InputStreamReader read = new InputStreamReader(new FileInputStream(file), ENCODING);
            // 檔案是否是檔案 和 是否存在
            if (file.isFile() && file.exists()) {
                wordSet = new HashSet<String>();
                // StringBuffer sb = new StringBuffer();
                // BufferedReader是包裝類,先把字元讀到緩存裡,到緩存滿了,再讀入記憶體,提高了讀的效率。
                BufferedReader br = new BufferedReader(read);
                String txt = null;
                // 讀取檔案,将檔案内容放入到set中
                while ((txt = br.readLine()) != null) {
                    wordSet.add(txt);
                }
                br.close();

                /*
                 * String str = sb.toString(); String[] ss = str.split(","); for
                 * (String s : ss) { wordSet.add(s); }
                 */
            }
            // 關閉檔案流
            read.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wordSet;
    }


    /**
     * 将HashSet中的敏感詞,存入HashMap中
     * @param wordSet
     * @return
     */
    private Map addSensitiveWordToHashMap(Set<String> wordSet) {

        // 初始化敏感詞容器,減少擴容操作
        Map wordMap = new HashMap(wordSet.size());
        for (String word : wordSet) {
            Map nowMap = wordMap;
            for (int i = 0; i < word.length(); i++) {
                 // 轉換成char型
                char keyChar = word.charAt(i);
                // 擷取
                Object tempMap = nowMap.get(keyChar);
                // 如果存在該key,直接指派
                if (tempMap != null) {
                    nowMap = (Map) tempMap;
                } else {
                    // 不存在則,則建構一個map,同時将isEnd設定為0,因為他不是最後一個
                    // 設定标志位
                    Map<String, String> newMap = new HashMap<String, String>();
                    newMap.put("isEnd", "0");
                    // 添加到集合
                    nowMap.put(keyChar, newMap);
                    nowMap = newMap;
                }
                // 最後一個
                if (i == word.length() - 1) {
                    nowMap.put("isEnd", "1");
                }
            }
        }
        return wordMap;
    }


}      

測試 Main.java:

package com.example.sensitivedemo.test;

/**
 * @Author : JCccc
 * @CreateTime : 2019/7/30
 * @Description :
 **/
public class Main {
    public static void main(String[] args) {
//需要屏蔽哪些字就在censorword.txt文檔内添加即可


        SensitiveFilterService filter = SensitiveFilterService.getInstance();
        String txt = "xx需要進行檢測的字元串xxx";
//如果需要過濾則用“”替換
//如果需要屏蔽,則用“*”替換
        String hou = filter.replaceSensitiveWord(txt, 1, "*");
        System.out.println("替換前的文字為:" + txt);
        System.out.println("替換後的文字為:" + hou);
    }
}