JAVA 簡單遮蔽詞處理
阿新 • • 發佈:2018-12-22
1.建立一個.properties的檔案,我這裡建立的是word.properties,裡面書寫有你想要遮蔽的敏感詞;
2.建立一個類幫助類,我這裡建立的是KeyWordFilter.java,具體實現程式碼ruxi
package com.boot.tool; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author YangJie * @Description:遮蔽詞工具類 * @Date:Created in 10:29 2018/2/2 * @Modified By: */ public class KeyWordFilter { private static Pattern pattern = null; /** * 從words.properties初始化正則表示式字串 */ private static void initPattern() { StringBuffer patternBuf = new StringBuffer(""); try { InputStream in = KeyWordFilter.class.getClassLoader().getResourceAsStream("words.properties"); Properties pro = new Properties(); pro.load(in); Enumeration enu = pro.propertyNames(); patternBuf.append("("); while (enu.hasMoreElements()) { patternBuf.append((String) enu.nextElement() + "|"); } patternBuf.deleteCharAt(patternBuf.length() - 1); patternBuf.append(")"); //unix換成UTF-8 //pattern = Pattern.compile(new String(patternBuf.toString().getBytes("ISO-8859-1"), "UTF-8")); //win下換成gb2312 pattern = Pattern.compile(new String(patternBuf.toString().getBytes("ISO-8859-1"), "gb2312")); } catch (IOException ioEx) { ioEx.printStackTrace(); } } /** * 遮蔽詞取代 */ private static String doFilter(String str) { Matcher m = pattern.matcher(str); //匹配到的詞用 ** 代替 str = m.replaceAll("****"); return str; } /** * main方法的測試 */ public static void main(String[] args) { String str = "黃色電影強姦,中國人民,你們都是大傻逼,只知道看小電影,色誘"; System.out.println("str:" + str); initPattern(); Date d1 = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss:SSS Z"); System.out.println("start:" + formatter.format(d1)); System.out.println("共" + str.length() + "個字元,查到" + KeyWordFilter.doFilter(str)); Date d2 = new Date(); System.out.println("end:" + formatter.format(d2)); } }