java,scala通过ansj分词 并做去除停词处理

本文介绍了如何在Java和Scala中使用ansj库进行文本分词,并结合停词表进行停词处理。首先,引入ansj的依赖,然后通过NlpAnalysis进行分词,接着读取停用词文件并更新词典,最后使用FilterModifWord过滤停用词。示例代码展示了如何实现这个过程。

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

下载ansj jar

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

java版本

List<Term> parse = NlpAnalysis.parse("山东威海隧道发生交通事故 造成9死1伤3人失踪");new NatureRecognition(parse).recognition(); //词性标注HashMap<String, String> strHashMap = new HashMap<String, String>();//读取停词文件String stopWordTable = "F://360downloads/StopWordTable.txt";File f = new File(stopWordTable);try { FileInputStream fileInputStream = new FileInputStream(f);//读入停用词文件 BufferedReader StopWordFileBr = new BufferedReader(new InputStreamReader(fileInputStream, "GBK")); String stopWord = null; for (; (stopWord = StopWordFileBr.readLine()) != null; ) { strHashMap.put(stopWord, "_stop"); } StopWordFileBr.close(); FilterModifWord.setUpdateDic(strHashMap); List<Term> term = FilterModifWord.modifResult(parse); //根据词性做一些业务上的判断 List list = new ArrayList(); for(int i=0;i<term.size();i++){ String word = term.get(i).getName(); //拿到词 String nature=term.get(i).getNatrue().toString().split(":")[0];//拿到词性 // System.out.println(word+":"+nature); if(nature.equals("d")){ if((term.get(i+1).getNatrue().toString().split(":")[0]).equals("a")){ String w = word+term.get(i+1).getName(); list.add(w); } }else{ if(i>0 && (term.get(i-1).getNatrue().toString().split(":")[0]).equals("d") && nature.equals("a")){ System.out.println("移除这一条数据"); }else{ list.add(word); } } } for(int i=0;i<list.size();i++){ System.out.println(list.get(i)); }} catch (Exception e) { e.printStackTrace();}

scala版本

val parse = ToAnalysis.parse("
山东威海隧道发生交通事故 造成9死1伤3人失踪
")//new NatureRecognition(parse).recognition(); //词性标注val strHashMap = new util.HashMap[String, String]val file = Source.fromFile("F://360downloads/StopWordTable.txt", "GBK")for (line <- file.getLines) { strHashMap.put(line, "_stop")}file.closeFilterModifWord.setUpdateDic(strHashMap)val term = FilterModifWord.modifResult(parse)System.out.println(term)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值