欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

敏感字过滤器

程序员文章站 2022-07-12 19:09:55
...

最近项目中要写一个过滤器来过滤玩家的脏话,敏感字词。现在写了个工具能直接使用,希望能帮到大家,看到请给我个赞,谢谢啦哈哈。

1. 代码

package com.wang;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class KeyFilterUtil {
    /*
     * 分隔符 ,
     * */
  public static void main(String[] args) {
    String a = "妈的aaa";
    String b = KeyFilterUtil.getFilt(a);
    System.out.println("before filter:" + a);
    System.out.println("after filter:"+b);
  }
  public static String getFilt(String stringSrc){
    String s=readFile(KeyFilterUtil.class.getClassLoader()
            .getResource("").getPath() + "/keyfilters.txt");
    //从文件中获取敏感字存入list
    List<String> keyList = keywordsToList(s);
    System.out.println("length:" + keyList.size());
    String filterString = stringSrc;
    for (int i = 0; i < keyList.size(); i++) {
        System.out.println(keyList.get(i) + "keyList.get(i)");
      if(stringSrc.contains(keyList.get(i))){
        filterString = stringSrc.replace(keyList.get(i),"*");
      }
    }
//    System.out.println("before filter:" + stringSrc);
//    System.out.println("after filter:"+filterString);
    return filterString;
  }

  public static List<String> keywordsToList(String s) {
    System.out.println("过滤关键字:"); 
    System.out.println(s);
    String[]result =s.split(",");
    List<String> list = new ArrayList<>();
    for (int i = 0; i < result.length; i++) {
      list.add(result[i]);
    }
    return list;
  }

  public static String readFile(String fliename){
      StringBuffer strbf=new StringBuffer();
      String s=null;
      char[] buf=new char[1024];
      try {
      FileReader f=new FileReader(fliename);
//        InputStreamReader f=new InputStreamReader(new FileInputStream(fliename),"UTF-8");
      while(f.read(buf)>0){
      strbf.append(buf);
      }
        s=strbf.toString();
        return s;
      } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
      } catch (IOException e) {
        e.printStackTrace();
        return null;
      }
  }
}

2. 目录结构

敏感字过滤器

3. keyfilters.txt内放入敏感词汇,用英文逗号分隔开

4.过滤效果图

敏感字过滤器