WordNet和JWI入门(一)
环境:JDK 10.0.2
IDE: Eclipse
基本介绍
-
WordNet WordNet是一个按照语义组织的英文词典,它把意思相近的单词构成一个同义词集组,然后以图的形式连接不同的同义词集组,意思越想近的词集组距离越短。通过WordNet我们可以很方便地找到一个词的同义词、上意词,或者仅仅是这个单词的解释。
-
JWI JWI是java使用WordNet的一个包,通过JWI我们才可以去调用WordNet。
下载与安装
- WordNet
首先我使用的是Mac OS X系统,安装WordNet最方便的方式就是使用Homebrew来安装,省去了一大堆配置上的麻烦:
brew install wordnet
如果报错,那么可能你需要安装一下Quartz。安装后在bash中输入wn,如果没有报错,那么安装成功 对于Windows用户,可以直接去官网下载
+JWI JWI直接下载jar包即可,然后在eclipse中导入库。如果你需要JWI文档,请点击这里。
查找同义词
public static void getSynsets() throws IOException {
String wnhome = "/usr/local/Cellar/wordnet/3.1";
String path = wnhome + File.separator + "dict";
File wnDir = new File(path);
URL url = new URL("file",null,path);
IDictionary dict = new Dictionary(url);
dict.open();
IIndexWord idxWord = dict.getIndexWord("math",POS.NOUN);
IWordID wordID = idxWord.getWordIDs().get(0);
IWord word = dict.getWord(wordID);
ISynset synset = word.getSynset();
for(IWord w:synset.getWords()) {
System.out.println(w.getLemma());
}
}
来对上面代码进行几点说明,首先是要配置wordnet路径,比如我的wordnet放在/usr/local/Cellar/wordnet/3.1路径中,那么我就要这样写:
String wnhome = "/usr/local/Cellar/wordnet/3.1";
然后获得URL对象,注意这里的URL对象是JWI包中而不是java原生库中的。 接着在open()打开字典之后,设置你要查找的单词,并且要设置词性,如果你的单词不在wordnet词典中,就会报错。 最后是获取同义词集合synset,打印出来即可。
查找上义词
查找上意词和同义词区别不大,这里直接给出代码和注释
public static void getHypernyms() throws IOException {
String wnhome = "/usr/local/Cellar/wordnet/3.1";
String path = wnhome + File.separator + "dict";
File wnDir = new File(path);
IDictionary dict = new Dictionary(wnDir);
dict.open();
IIndexWord idxWord = dict.getIndexWord("American",POS.NOUN);
IWordID wordID = idxWord.getWordIDs().get(0);
IWord word = dict.getWord(wordID);
ISynset synset = word.getSynset();
List<ISynsetID> hypernyms = synset.getRelatedSynsets(Pointer.HYPERNYM);
List<IWord> words;
for(ISynsetID isid : hypernyms) {
words = dict.getSynset(isid).getWords();
for(Iterator<IWord> i=words.iterator();i.hasNext();) {
System.out.print(i.next().getLemma());
if(i.hasNext()) {
System.out.println(",");
}
}
}
}
Thank You For Reading