java使用nlp工具完成英文词性还原、分词
前言
在一些英文处理的业务中,有时候会面临一些场景:判断这个单词是否在当前句子中,但英文相对比较棘手的问题是有很多词汇的变形如单复数、过去时、现在进行时、将来时等等,这样采用简单的字符串匹配操作肯定是不合适了,因此一直需要一个nlp分词器将句子中词汇分开、词性还原等。
正好找到了一个斯坦福提供的nlp java工具包,可以有多种语言的:词性标注(part-of-speech (POS) tagger)、命名实体识别(named entity recognizer (NER))、情感分析(sentiment analysis)等功能,我们拿来做词性还原是有点大材小用了。
使用stanford nlp
下面我们就来使用一下这个工具,先引入相应的包,使用maven如下:
<!--stanford nlp core-->
<dependency>
<groupId>edu.stanford.nlp</groupId>
<artifactId>stanford-corenlp</artifactId>
<version>3.9.2</version>
</dependency>
<!--stanford nlp model-->
<dependency>
<groupId>edu.stanford.nlp</groupId>
<artifactId>stanford-corenlp</artifactId>
<version>3.9.2</version>
<classifier>models</classifier>
</dependency>
使用jar包在这里下载 https://stanfordnlp.github.io/CoreNLP/download.html,如下图:
demo
demo如下,在demo中输入的一堆字符串包括几句话、一个网址、词组等,其中可以看到,一句完整的话中,每个词都获取了其最原始的词性,但是网址中的英文却不行,而且复合词,中间带-的词比如hard-working,应该是视为了一个词,因此working并没有转换为原词。
package com.example.test.stanfornlp;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.util.CoreMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class Test {
public static void main(String[] args) {
String str = "2 running Quick brown-foxes leap over lazy dogs in the summer evening. https://blog.csdn.net/LS7011846/article/details/101151185";
List<String> wordList = getOriginalText(str);
for (String word:wordList) {
System.out.println(word);
}
}
/**
* 根据string获取对应原始词性词汇列表
* @param text
* @return
*/
public static List<String> getOriginalText(String text){
List<String> wordList = new ArrayList<>();
Properties properties = new Properties();
//分词、分句、词性标注和次元信息。
properties.put("annotators","tokenize,ssplit,pos,lemma");
StanfordCoreNLP pipeline = new StanfordCoreNLP(properties);
Annotation document = new Annotation(text);
pipeline.annotate(document);
List<CoreMap> words = document.get(CoreAnnotations.SentencesAnnotation.class);
for(CoreMap wordTemp: words) {
for (CoreLabel token: wordTemp.get(CoreAnnotations.TokensAnnotation.class)) {
String originalWord = token.get(CoreAnnotations.LemmaAnnotation.class); // 获取对应上面word的词元信息,即我所需要的词形还原后的单词
wordList.add(originalWord);
}
}
return wordList;
}
}
输出如下:
2
run
quick
brown-fox
leap
over
lazy
dog
in
the
summer
evening
,
long-distance
telephone
,
hard-working
people
,
https://blog.csdn.net/ls7011846/article/details/101151185
结语
以上只是使用stanfornlp来做了英语句子词汇原型的还原,只是没找到其他合适的工具 哈哈杀鸡焉用牛刀,如果有想做nlp相关的伙伴可以多关注这些。
参考文档:https://stanfordnlp.github.io/CoreNLP/download.html