java过滤文章中的敏感词的小例题

本文介绍了一种使用Java实现的敏感词过滤方法,通过读取配置文件中的敏感词汇并利用正则表达式进行匹配替换,实现了文本内容的快速审查与净化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

做博客或bbs时;文章中经常会有些敏感词要去掉;
以下是一个java实现这个功能的小例题:
2个文件words.properties和KeyWordFilter.java;
1、words.properties文件是个文本文件;内容如下:
敏感词一
敏感词二
敏感词三
 
2、KeyWordFilter.java是个java文件内容如下:
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.Pattern;
import java.util.regex.Matcher;
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(")");
 
  pattern = Pattern.compile(new String(patternBuf.toString().getBytes("ISO-8859-1"), "UTF-8"));
 
 }catch(IOException ioEx){
 
  ioEx.printStackTrace();
 
 }
 
}
 private static String doFilter(String str){
 
 Matcher m = pattern.matcher(str);
 
 str = m.replaceAll("");
 
 return str;
 
}
 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));
 
}
 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值