首先pom文件引入Ansj的依赖
<!-- ansj依赖jar配置 ==start -->
<dependency>
<groupId>org.ansj</groupId>
<artifactId>ansj_seg</artifactId>
<version>5.1.1</version>
</dependency>
<!-- ansj依赖jar配置 ==end -->
这里写一个Ansj的一个测试代码
输入为需要分词的字符串,和需要过滤的词性
具体词性介绍可以看:
https://github.com/NLPchina/ansj_seg/wiki/%E8%AF%8D%E6%80%A7%E6%A0%87%E6%B3%A8%E8%A7%84%E8%8C%83
输出为过滤后的词语用\001相连的字符串
public static void test(String input, String natureStr){
String [] arraystr= natureStr.split(",");//将词性字符串切割
StringBuilder sb=new StringBuilder();
Set<String> set =new HashSet<String>();//将每一个词性作为元素放如set集合中
for(String arr:arraystr){
set.add(arr);
}
Result result =NlpAnalysis.parse(input);//核心代码,将输入字符串经行分词,返回一个为Result类型的值,样式为 词/词性,词/词性
List<Term>list =result.getTerms();//将每一个分词和词性放入list集合,每一个词+词性为list的一个元素 样式为[词/词性,词/词性]
int count=0;
for(Term term:list){
if(set.contains(term.getNatureStr())){//判断所分割的词的词性中是否存在set集合中的词性。getNatureStr方法只拿出词性
if (count>0){
sb.append('\001');
}
sb.append(term.getName());//只拼接词
count++;
}
}
System.out.println(sb.toString());
}
public static void main(String[] args) {
String natureList = "n,nr,nr1,nr2,nrj,nrf,ns,nsf,nt,nz,nl,ng,nw,s,v,vd,vn,vf,vx,vi,vl,vg,a,ad,an,ag,al,x,xx";
test("输入一个字符串",natureList);
}
以上为Ansj分词器的简单使用