导包
<!-- https://mvnrepository.com/artifact/org.ansj/ansj_seg -->
<dependency>
<groupId>org.ansj</groupId>
<artifactId>ansj_seg</artifactId>
<version>5.1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.nlpcn/nlp-lang -->
<dependency>
<groupId>org.nlpcn</groupId>
<artifactId>nlp-lang</artifactId>
<version>1.7.7</version>
</dependency>
基本使用
ansj分词有四种模式:
基本分词-BaseAnalysis
用户自定义词典 | 数字识别 | 人名识别 | 机构名识别 | 新词发现 |
Χ | √ | Χ | Χ | Χ |
精准分词-ToAnalysis
用户自定义词典 | 数字识别 | 人名识别 | 机构名识别 | 新词发现 |
√ | √ | √ | Χ | Χ |
nlp分词-NlpAnalysis
用户自定义词典 | 数字识别 | 人名识别 | 机构名识别 | 新词发现 |
√ | √ | √ | √ | √ |
面向索引分词-IndexAnalysis
用户自定义词典 | 数字识别 | 人名识别 | 机构名识别 | 新词发现 |
√ | √ | √ | Χ | Χ |
精准分词是店长推荐款,如果想马上上手使用,推荐用精准分词的方式:
val str = "这是一个诈骗短信,恭喜您中奖啦!http://regxlib.com/Default.aspx"
val result = ToAnalysis.parse(str)
println(result)
显示结果:
这/r,是/v,一个/m,诈骗/vn,短信/n,,/w,恭喜/v,您/r,中奖/v,啦/y,!/w
过滤词
用户还可以通过创建StopRecognition()来进行过滤,例如:
val filter = new StopRecognition()
filter.insertStopNatures("w",null) //过滤掉标点和null
用户自定义词库
自定义词库的好处就是可以按照你自己的方式定义词,例如“这是一个诈骗短信”里的“这是”,按照ansj原来的分词方式,会将“这是”分为:这/r,是/v,你可以将“这是”认定为一个词,并且可以自定义这个词的属性,岂不是美滋滋?
1.在resource目录下,创建library目录,创建userLibrary.dic文件:
2.在文件中写入内容:
这是 r 1000
注意:中间分割付一定是\t
3.代码:
import org.nlpcn.commons.lang.tire.library.Library
val forest = Library.makeForest(classOf[Nothing].getResourceAsStream("/library/userLibrary.dic")) //加载字典文件
val filter = new StopRecognition()
filter.insertStopNatures("w") //过滤掉标点
val str = "这是一个诈骗短信,恭喜您中奖啦!"
val result = ToAnalysis.parse(str,forest)
.recognition(filter)// 过滤掉标点
.toStringWithOutNature(",")// 分词默认会打出词性,此语句用于不打出词性,并且分好的词用“,”隔开
println(result)
结果:
这是,一个,诈骗,短信,恭喜,您,中奖,啦
Ansj分词 使用手册:http://nlpchina.github.io/ansj_seg/?tdsourcetag=s_pctim_aiomsg