Java---根据停用词表对文本进行过滤

根据停用词表内的停用词,删除文本中的包含的这些停用词
1、先构建停用词的Map表,方便后续判断 词 是否在该Map表内
2、对句子进行分词,过滤

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;

public class filterstopword {
	
	//停用词表路径
	public static String stop_word_path = "D:/Document/data/stop_word.txt";
	public static Map<String, Integer> map; //停用词map表
	
	public static void main(String[] args) throws IOException {
		map = getMap();
		String sentence = "xxxxxx";
		System.out.println(RemoveStopWords(sentence));
	}
	
	/**
     * 根据停用词表,过滤句子中包含的停用词
     * @param oldString:原中文文本
     * @return 去除停用词之后的中文文本
     * @throws IOException
     */
    public static String RemoveStopWords(String oldString) throws IOException {
        String newString = "";
		// 首先对句子进行分词
		List<Term> terms = ToAnalysis.parse(oldString).getTerms();
		System.out.println(terms);
		
		// 遍历分词后的每个词,看它是否在map中,若在则过滤,若不在,则保存
		for (int i = 0; i < terms.size(); i++) {
			String word = terms.get(i).getName(); // 拿到词
			if (!map.containsKey(word)){ // 判断该词是否在停用词字典内
				String temp = " " + word;
				newString += temp;
			}
		}
        return newString;
    }
    
    /**
	 * 获取停用词的map形式
	 * @return
	 * @throws IOException
	 */
	public static Map<String, Integer> getMap() throws IOException {
		Map<String, Integer> Dic = new HashMap<String, Integer>();
		// 加载字典
		InputStreamReader isr = new InputStreamReader(new FileInputStream(stop_word_path), "UTF-8");
		BufferedReader br = new BufferedReader(isr);
		String line = "";
		while ((line = br.readLine()) != null) {
			Dic.put(line.trim(), 1);
		}
		// 关闭文件
		br.close();
		isr.close();

		return Dic;
	} 
}

分词器所使用的的jar包依赖

		<dependency>
			<groupId>org.ansj</groupId>
			<artifactId>ansj_seg</artifactId>
			<version>5.1.1</version>
		</dependency>

完!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值