I recently figured out how to setup the Java WordNet Library (JWNL) for something I needed to do at work. Prior to this, I have been largely unsuccessful at figuring out how to access Wordnet from Java, unless you count my one attempt to use the Java Wordnet Interface (JWI) described here. I think there are two main reason for this. First, I just didn't try hard enough, since I could get by before this without having to hook up Wordnet from Java. The second reason was the over-supply of libraries (JWNL, JWI, RiTa, JAWS, WS4j, etc), each of which annoyingly stops short of being full-featured in one or more significant ways.
The one Wordnet interface that I know that doesn't suffer from missing features comes with the Natural Language ToolKit (NLTK) library (written in Python). I have used it in the past to access Wordnet for data pre-processing tasks. In this particular case, I needed to call it at runtime from within a Java application, so I finally bit the bullet and chose a library to integrate into my application - I chose JWNL based on seeing it being mentioned in the Taming Text book (and used in the code samples). I also used code snippets from Daniel Shiffman's Wordnet page to learn about the JWNL API.
After I had successfully integrated JWNL, I figured it would be cool (and useful) if I could build an interface (in Scala) that looked like the NLTK Wordnet interface. Plus, this would also teach me how to use JWNL beyond the basic stuff I needed for my webapp. My list of functions were driven by the examples from the Wordnet section (2.5) from the NLTK book and the examples from the NLTK Wordnet Howto. My Scala class implements most of the functions mentioned on these two pages. The following session will give you an idea of the coverage - even though it looks a Python interactive session, it was generated by my JUnit test. I do render the Synset and Word (Lemma) objects using custom format() methods to preserve the illusion (and to make the output readable), but if you look carefully, you will notice the rendering of List() is Scala's and not Python's.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | >>> wn.synsets('motorcar')
List(car.n.01)
>>> wn.synset('car.n.01').lemma_names
List(car, auto, automobile, machine, motorcar)
>>> sorted([lemma.name for synset
... in types_of_motorcar for lemma in synset.lemmas])
List(Model_T, Stanley_Steamer, ambulance, beach_wagon, bus, \
cab, compact, convertible, coupe, cruiser, electric, gas_guzzler, \
hardtop, hatchback, horseless_carriage, hot_rod, jeep, limousine, \
loaner, minicar, minivan, pace_car, racer, roadster, sedan, \
sport_utility, sports_car, stock_car, subcompact, touring_car, used-car)
>>> wn.synset('car.n.01').definition
a motor vehicle with four wheels; usually propelled by an internal \
combustion engine
>>> wn.synset('car.n.01').examples
List("he needs a car to get to work")
>>> wn.synset('car.n.01').lemmas
List(car.n.01.car, car.n.02.auto, car.n.03.automobile, \
car.n.04.machine, car.n.05.motorcar)
>>> wn.lemma('car.n.01.automobile').name
automobile
>>> for synset in wn.synsets('car'):
... print synset.lemma_names
...
[car, auto, automobile, machine, motorcar]
[car, railcar, railway_car, railroad_car]
[car, gondola]
[car, elevator_car]
[cable_car, car]
>>> wn.lemmas('car')
List(car.n.01.car, car.n.01.car, car.n.01.car, car.n.01.car, \
cable_car.n.02.car)
>>> motorcar = wn.synset('car.n.01')
>>> types_of_motorcar = motorcar.hyponyms()
>>> types_of_motorcar
List(ambulance.n.01, beach_wagon.n.01, bus.n.01, cab.n.01, \
compact.n.01, convertible.n.01, coupe.n.01, cruiser.n.01, \
electric.n.01, gas_guzzler.n.01, hardtop.n.01, hatchback.n.01, \
horseless_carriage.n.01, hot_rod.n.01, jeep.n.01, limousine.n.01, \
loaner.n.01, minicar.n.01, minivan.n.01, Model_T.n.01, pace_car.n.01, \
racer.n.01, roadster.n.01, sedan.n.01, sports_car.n.01, \
sport_utility.n.01, Stanley_Steamer.n.01, stock_car.n.01, \
subcompact.n.01, touring_car.n.01, used-car.n.01)
>>> types_of_motorcar[0]
ambulance.n.01
>> motorcar.hypernyms()
List(motor_vehicle.n.01)
>>> paths = motorcar.hypernym_paths()
>>> len(paths)
2
>>> [synset.name for synset in paths[0]]
List(car.n.01, motor_vehicle.n.01, self-propelled_vehicle.n.01, \
wheeled_vehicle.n.01, vehicle.n.01, conveyance.n.01, \
instrumentality.n.01, artifact.n.01, whole.n.01, object.n.01, \
physical_entity.n.01, entity.n.01)
>>> [synset.name for synset in paths[1]]
List(car.n.01, motor_vehicle.n.01, self-propelled_vehicle.n.01, \
wheeled_vehicle.n.01, container.n.01, instrumentality.n.01, \
artifact.n.01, whole.n.01, object.n.01, physical_entity.n.01, \
entity.n.01)
>>> motorcar.root_hypernyms()
List(entity.n.01)
>>> wn.synset('tree.n.01').part_meronyms()
List(stump.n.01, crown.n.01, limb.n.01, trunk.n.01, burl.n.01)
>>> wn.synset('tree.n.01').substance_meronyms()
List(sapwood.n.01, heartwood.n.01)
>>> wn.synset('tree.n.01').member_holonyms()
List(forest.n.01)
>>> for synset in wn.synsets('mint', wn.NOUN):
... print synset.name + ':', synset.definition
...
batch.n.01: (often followed by `of') a large number or amount or extent
mint.n.01: any north temperate plant of the genus Mentha with aromatic \
leaves and small mauve flowers
mint.n.01: any member of the mint family of plants
mint.n.01: the leaves of a mint plant used fresh or candied
mint.n.01: a candy that is flavored with a mint oil
mint.n.01: a plant where money is coined by authority of the government
>>> wn.synset('mint.n.04').part_holonyms()
List(mint.n.01)
>>> [x.definition for x
... in wn.synset('mint.n.04').part_holonyms()]
List(any north temperate plant of the genus Mentha with aromatic leaves \
and small mauve flowers)
>>> wn.synset('mint.n.04').substance_holonyms()
List(mint.n.01)
>>> [x.definition for x
... in wn.synset('mint.n.04').substance_holonyms()]
List(a candy that is flavored with a mint oil)
>>> wn.synset('walk.v.01').entailments()
List(step.v.01)
>>> wn.synset('eat.v.01').entailments()
List(chew.v.01, swallow.v.01)
>>> wn.synset('tease.v.03').entailments()
List(arouse.v.01, disappoint.v.01)
>>> wn.lemma('supply.n.02.supply').antonyms()
List(demand.n.01.demand)
>>> wn.lemma('rush.v.01.rush').antonyms()
List(linger.v.01.linger)
>>> wn.lemma('horizontal.a.01.horizontal').antonyms()
List(vertical.a.01.vertical, inclined.a.01.inclined)
>>> wn.lemma('staccato.r.01.staccato').antonyms()
List(legato.r.01.legato)
>>> right = wn.synset('right_whale.n.01')
>>> orca = wn.synset('orca.n.01')
>>> minke = wn.synset('minke_whale.n.01')
>>> tortoise = wn.synset('tortoise.n.01')
>>> novel = wn.synset('novel.n.01')
>>> right.lowest_common_hypernyms(minke)
List(baleen_whale.n.01)
>>> right.lowest_common_hypernyms(orca)
List(whale.n.01)
>>> right.lowest_common_hypernyms(tortoise)
List(vertebrate.n.01)
>>> right.lowest_common_hypernyms(novel)
List(entity.n.01)
>>> wn.synset('baleen_whale.n.01').min_depth()
14
>>> wn.synset('whale.n.02').min_depth()
13
>>> wn.synset('vertebrate.n.01').min_depth()
8
>>> wn.synset('entity.n.01').min_depth()
0
>>> right.path_similarity(minke)
0.25
>>> right.path_similarity(orca)
0.16666666666666666
>>> right.path_similarity(tortoise)
0.07692307692307693
>>> right.path_similarity(novel)
0.043478260869565216
>>> dog = wn.synset('dog.n.01')
>>> cat = wn.synset('cat.n.01')
>>> hit = wn.synset('hit.v.01')
>>> slap = wn.synset('slap.v.01')
>>> dog.path_similarity(cat)
0.2
>>> hit.path_similarity(slap)
0.14285714285714285
>>> dog.lch_similarity(cat)
2.0794415416798357
>>> hit.lch_similarity(slap)
1.3862943611198906
>>> dog.wup_similarity(cat)
0.8666666666666667
>>> hit.wup_similarity(slap)
0.25
>>> dog.res_similarity(cat)
7.2549003421277245
>>> hit.res_similarity(slap)
>>> dog.jcn_similarity(cat)
0.537382154955756
>>> dog.lin_similarity(cat)
0.8863288628086228
>>> for synset in list(wn.all_synsets('n'))[:10]:
... print(synset)
...
'hood.n.01
The_Hague.n.01
twenty-two.n.01
zero.n.01
one.n.01
lauryl_alcohol.n.01
one-hitter.n.01
ten.n.01
hundred.n.01
thousand.n.01
>>> print(wn.morphy('denied', wn.VERB))
deny
>>> print(wn.morphy('dogs'))
dog
>>> print(wn.morphy('churches'))
church
>>> print(wn.morphy('aardwolves'))
aardwolf
>>> print(wn.morphy('abaci'))
abacus
>>> print(wn.morphy('book', wn.NOUN))
book
>>> wn.morphy('hardrock', wn.ADV)
>>> wn.morphy('book', wn.ADJ)
>>> wn.morphy('his', wn.NOUN)
|
Under the hood, my interface uses the Wordnet Similarity for Java (WS4j) for the similarity implementations (which JWNL doesn't contain) and JWNL for everything else. The various Similarity measures are described in this paper (PDF) by the authors of the Perl module Wordnet::Similarity, upon which WS4j is based.
Before you can start, you need to download Wordnet (of course). You can skip the installation process unless you also want to access Wordnet functionality directly from your operating system. I installed my Wordnet dictionary under /opt/wordnet-3.0.
Next, you will need to download JWNL. You should download the JWNL source because your client will need an XML configuration file that comes with the source download. Find the file config/file_properties.xml and change the value of the param@value attribute where param@name == "dictionary_path". The value should be the path to your Wordnet dict directory - in my case it is /opt/wordnet-3.0/dict. You also need to update the jwnl_properties/version@number from 2.0 to 3.0 otherwise you will get errors during starting up your code. This file should go somewhere on your classpath - my build tool is sbt (same for mvn), so I put it into src/main/resources/wnconfig.xml.
The JWNL source distribution also contains the JWNL JAR file, so I put this into the lib (unmanaged) subdirectory. I could also have gotten it from Maven Central.
Next, I downloaded the WS4j JAR. This JAR needs to be unmanaged because its not available in Maven Central, so it goes into the lib subdirectory of my project. You need to get the JAR (rather than build from source) because it packages several classes (from the JAWJAW project) that are not included in the source. However, the source was useful for me because it showed me how I could convert from JWNL Synsets to WS4j Concept objects and call the various Similarity measures.
Here is the code for my NLTK-like Wordnet interface. As you can see, it differs from the NLTK version in that it does not support fluent interfaces. So for example, you cannot call wn.synset('car.n.01').definition(). Instead you must call wn.definition(wn.synset("car", POS.NOUN, 1)). This is because JWNL implements its own Synset and Word (analogous to NLTK's Lemma) classes. Supporting the fluent interfaces would have meant subclassing these classes, which would have made the code a bit confusing, so I didn't do it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | // Source: src/main/scala/com/mycompany/scalcium/utils/Wordnet.scala
package com.mycompany.scalcium.utils
import java.io.File
import java.io.FileInputStream
import scala.Array.canBuildFrom
import scala.collection.JavaConversions.asScalaBuffer
import scala.collection.JavaConversions.asScalaIterator
import scala.collection.TraversableOnce.flattenTraversableOnce
import scala.collection.mutable.ArrayBuffer
import edu.cmu.lti.jawjaw.util.WordNetUtil
import edu.cmu.lti.lexical_db.NictWordNet
import edu.cmu.lti.lexical_db.data.Concept
import edu.cmu.lti.ws4j.RelatednessCalculator
import edu.cmu.lti.ws4j.impl.JiangConrath
import edu.cmu.lti.ws4j.impl.LeacockChodorow
import edu.cmu.lti.ws4j.impl.Lesk
import edu.cmu.lti.ws4j.impl.Lin
import edu.cmu.lti.ws4j.impl.Path
import edu.cmu.lti.ws4j.impl.Resnik
import edu.cmu.lti.ws4j.impl.WuPalmer
import net.didion.jwnl.JWNL
import net.didion.jwnl.data.IndexWord
import net.didion.jwnl.data.POS
import net.didion.jwnl.data.PointerType
import net.didion.jwnl.data.PointerUtils
import net.didion.jwnl.data.Synset
import net.didion.jwnl.data.Word
import net.didion.jwnl.data.list.PointerTargetNode
import net.didion.jwnl.data.list.PointerTargetNodeList
import net.didion.jwnl.dictionary.Dictionary
class Wordnet(val wnConfig: File) {
JWNL.initialize(new FileInputStream(wnConfig))
val dict = Dictionary.getInstance()
val lexdb = new NictWordNet()
val Path_Similarity = new Path(lexdb)
val LCH_Similarity = new LeacockChodorow(lexdb)
val WUP_Similarity = new WuPalmer(lexdb)
val RES_Similarity = new Resnik(lexdb)
val JCN_Similarity = new JiangConrath(lexdb)
val LIN_Similarity = new Lin(lexdb)
val Lesk_Similarity = new Lesk(lexdb)
def allSynsets(pos: POS): Stream[Synset] =
dict.getIndexWordIterator(pos)
.map(iword => iword.asInstanceOf[IndexWord])
.map(iword => iword.getSenses())
.flatten
.toStream
def synsets(lemma: String): List[Synset] = {
POS.getAllPOS()
.map(pos => pos.asInstanceOf[POS])
.map(pos => synsets(lemma, pos))
.flatten
.toList
}
def synsets(lemma: String, pos: POS): List[Synset] = {
val iword = dict.getIndexWord(pos, lemma)
if (iword == null) List.empty[Synset]
else iword.getSenses().toList
}
def synset(lemma: String, pos: POS,
sid: Int): Option[Synset] = {
val iword = dict.getIndexWord(pos, lemma)
if (iword != null) Some(iword.getSense(sid))
else None
}
def lemmas(s: String): List[Word] = {
synsets(s)
.map(ss => lemmas(Some(ss)))
.flatten
.filter(w => w.getLemma().equals(s))
}
def lemmas(oss: Option[Synset]): List[Word] = {
oss match {
case Some(ss) => ss.getWords().toList
case _ => List.empty[Word]
}
}
def lemma(oss: Option[Synset], wid: Int): Option[Word] = {
oss match {
case Some(x) => Option(lemmas(oss)(wid))
case None => None
}
}
def lemma(oss: Option[Synset], lem: String): Option[Word] = {
oss match {
case Some(ss) => {
val words = ss.getWords()
.filter(w => lem.equals(w.getLemma()))
if (words.size > 0) Some(words.head)
else None
}
case None => None
}
}
////////////////// similarities /////////////////////
def pathSimilarity(loss: Option[Synset],
ross: Option[Synset]): Double =
getPathSimilarity(loss, ross, Path_Similarity)
def lchSimilarity(loss: Option[Synset],
ross: Option[Synset]): Double =
getPathSimilarity(loss, ross, LCH_Similarity)
def wupSimilarity(loss: Option[Synset],
ross: Option[Synset]): Double =
getPathSimilarity(loss, ross, WUP_Similarity)
// WS4j Information Content Finder (ICFinder) uses
// SEMCOR, Resnik, JCN and Lin similarities are with
// the SEMCOR corpus.
def resSimilarity(loss: Option[Synset],
ross: Option[Synset]): Double =
getPathSimilarity(loss, ross, RES_Similarity)
def jcnSimilarity(loss: Option[Synset],
ross: Option[Synset]): Double =
getPathSimilarity(loss, ross, JCN_Similarity)
def linSimilarity(loss: Option[Synset],
ross: Option[Synset]): Double =
getPathSimilarity(loss, ross, LIN_Similarity)
def leskSimilarity(loss: Option[Synset],
ross: Option[Synset]): Double =
getPathSimilarity(loss, ross, Lesk_Similarity)
def getPathSimilarity(loss: Option[Synset],
ross: Option[Synset],
sim: RelatednessCalculator): Double = {
val lconcept = getWS4jConcept(loss)
val rconcept = getWS4jConcept(ross)
if (lconcept == null || rconcept == null) 0.0D
else sim.calcRelatednessOfSynset(lconcept, rconcept)
.getScore()
}
def getWS4jConcept(oss: Option[Synset]): Concept = {
oss match {
case Some(ss) => {
val pos = edu.cmu.lti.jawjaw.pobj.POS.valueOf(
ss.getPOS().getKey())
val synset = WordNetUtil.wordToSynsets(
ss.getWord(0).getLemma(), pos)
.head
new Concept(synset.getSynset(), pos)
}
case _ => null
}
}
////////////////// Morphy ///////////////////////////
def morphy(s: String, pos: POS): String = {
val bf = dict.getMorphologicalProcessor()
.lookupBaseForm(pos, s)
if (bf == null) "" else bf.getLemma()
}
def morphy(s: String): String = {
val bases = POS.getAllPOS().map(pos =>
morphy(s, pos.asInstanceOf[POS]))
.filter(str => (! str.isEmpty()))
.toSet
if (bases.isEmpty) "" else bases.toList.head
}
////////////////// Synset ///////////////////////////
def lemmaNames(oss: Option[Synset]): List[String] = {
oss match {
case Some(ss) => ss.getWords()
.map(word => word.getLemma())
.toList
case _ => List.empty[String]
}
}
def definition(oss: Option[Synset]): String = {
oss match {
case Some(ss) => {
ss.getGloss()
.split(";")
.filter(s => !isQuoted(s.trim))
.mkString(";")
}
case _ => ""
}
}
def examples(oss: Option[Synset]): List[String] = {
oss match {
case Some(ss) => {
ss.getGloss()
.split(";")
.filter(s => isQuoted(s.trim))
.map(s => s.trim())
.toList
}
case _ => List.empty[String]
}
}
def hyponyms(oss: Option[Synset]): List[Synset] =
relatedSynsets(oss, PointerType.HYPONYM)
def hypernyms(oss: Option[Synset]): List[Synset] =
relatedSynsets(oss, PointerType.HYPERNYM)
def partMeronyms(oss: Option[Synset]): List[Synset] =
relatedSynsets(oss, PointerType.PART_MERONYM)
def partHolonyms(oss: Option[Synset]): List[Synset] =
relatedSynsets(oss, PointerType.PART_HOLONYM)
def substanceMeronyms(oss: Option[Synset]): List[Synset] =
relatedSynsets(oss, PointerType.SUBSTANCE_MERONYM)
def substanceHolonyms(oss: Option[Synset]): List[Synset] =
relatedSynsets(oss, PointerType.SUBSTANCE_HOLONYM)
def memberHolonyms(oss: Option[Synset]): List[Synset] =
relatedSynsets(oss, PointerType.MEMBER_HOLONYM)
def entailments(oss: Option[Synset]): List[Synset] =
relatedSynsets(oss, PointerType.ENTAILMENT)
def entailedBy(oss: Option[Synset]): List[Synset] =
relatedSynsets(oss, PointerType.ENTAILED_BY)
def relatedSynsets(oss: Option[Synset],
ptr: PointerType): List[Synset] = {
oss match {
case Some(ss) => ss.getPointers(ptr)
.map(ptr => ptr.getTarget().asInstanceOf[Synset])
.toList
case _ => List.empty[Synset]
}
}
def hypernymPaths(oss: Option[Synset]): List[List[Synset]] = {
oss match {
case Some(ss) => PointerUtils.getInstance()
.getHypernymTree(ss)
.toList
.map(x => x.asInstanceOf[PointerTargetNodeList])
.map(ptnl => ptnl
.map(x => x.asInstanceOf[PointerTargetNode])
.map(ptn => ptn.getSynset())
.toList)
.toList
case _ => List.empty[List[Synset]]
}
}
def rootHypernyms(oss: Option[Synset]): List[Synset] = {
hypernymPaths(oss)
.map(hp => hp.reverse.head)
.toSet
.toList
}
def lowestCommonHypernym(loss: Option[Synset],
ross: Option[Synset]): List[Synset] = {
val lpaths = hypernymPaths(loss)
val rpaths = hypernymPaths(ross)
val pairs = for (lpath <- lpaths; rpath <- rpaths)
yield (lpath, rpath)
val lchs = ArrayBuffer[(Synset,Int)]()
pairs.map(pair => {
val lset = Set(pair._1).flatten
val matched = pair._2
.zipWithIndex
.filter(si => lset.contains(si._1))
if (! matched.isEmpty) lchs += matched.head
})
val lchss = lchs.sortWith((a, b) => a._2 < b._2)
.map(lc => lc._1)
.toList
if (lchss.isEmpty) List.empty[Synset]
else List(lchss.head)
}
def minDepth(oss: Option[Synset]): Int = {
val lens = hypernymPaths(oss)
.map(path => path.size)
.sortWith((a,b) => a > b)
if (lens.isEmpty) -1 else (lens.head - 1)
}
def format(ss: Synset): String = {
List(ss.getWord(0).getLemma(),
ss.getPOS().getKey(),
(ss.getWord(0).getIndex() + 1).formatted("%02d"))
.mkString(".")
}
/////////////////// Words / Lemmas ////////////////////
def antonyms(ow: Option[Word]): List[Word] =
relatedLemmas(ow, PointerType.ANTONYM)
def relatedLemmas(ow: Option[Word],
ptr: PointerType): List[Word] = {
ow match {
case Some(w) => w.getPointers(ptr)
.map(ptr => ptr.getTarget().asInstanceOf[Word])
.toList
case _ => List.empty[Word]
}
}
def format(w : Word): String = {
List(w.getSynset().getWord(0).getLemma(),
w.getPOS().getKey(),
(w.getIndex() + 1).formatted("%02d"),
w.getLemma())
.mkString(".")
}
////////////////// misc ////////////////////////////////
def isQuoted(s: String): Boolean = {
if (s.isEmpty()) false
else (s.charAt(0) == '"' &&
s.charAt(s.length() - 1) == '"')
}
}
|
There are some other, more subtle differences. If you look at the output of wn.lemmas('car'), the output from NLTK is List[Lemma](car.n.01.car, car.n.02.car, car.n.03.car, car.n.04.car, cable_car.n.01.car). On the other hand, the output from my Scala code is List[Word](car.n.01.car, car.n.01.car, car.n.01.car, car.n.01.car, cable_car.n.02.car). This is because NLTK puts the Synset ID in the third position. My JWNL based wn.lemmas() method returns a List of Synsets, each Synset containing a List of Words, and provides a Word.id value which refers to the position of the Word within the Synset. Since my formatting method does not have access to the id of the Synset, it is not able to populate the third position correctly.
Another difference, which is not that critical (once you know it, you can work around it) is that NLTK's and my version of wn.hyponyms() return synsets in opposite order. Also my allSynsets() returns Synsets in a different order than does NLTK's wn.all_synsets() call.
Some of the WS4j Similarity measures depend on the Information Content, which in turn depends on a corpus being analyzed. NLTK provides access to a many corpora and allows the user to specify what corpus should be used to calculate the Information Content. WS4j uses the SEMCOR corpus, and does not allow it to be overriden as far as I can tell.
The JUnit code below shows how to call the methods in the Wordnet.scala class. Each test case roughly corresponds to a block in the session above, and closely mimics the calls in the NLTK Chapter 2 and HOWTO pages. All exceptions are clearly marked in the Javadocs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 | // Source: src/test/scala/com/mycompany/scalcium/utils/WordnetTest.scala
package com.mycompany.scalcium.utils
import java.io.File
import org.junit.Assert
import org.junit.Test
import net.didion.jwnl.data.POS
class WordnetTest {
val wn = new Wordnet(new File("src/main/resources/wnconfig.xml"))
/**
* >>> from nltk.corpus import wordnet as wn
* >>> wn.synsets('motorcar')
* [Synset('car.n.01')]
*/
@Test
def testSynsets(): Unit = {
Console.println(">>> wn.synsets('motorcar')")
val motorcar = wn.synsets("motorcar")
Console.println(motorcar.map(m => wn.format(m)))
Assert.assertNotNull(motorcar)
}
/**
* >>> wn.synset('car.n.01').lemma_names
* ['car', 'auto', 'automobile', 'machine', 'motorcar']
*/
@Test
def testSynsetLemmaNames(): Unit = {
Console.println(">>> wn.synset('car.n.01').lemma_names")
val lms = wn.lemmaNames(wn.synset("car", POS.NOUN, 1))
Console.println(lms)
Assert.assertEquals(5, lms.size)
}
/**
* >>> wn.synset('car.n.01').definition
* 'a motor vehicle with four wheels; usually propelled by \
* an internal combustion engine'
*/
@Test
def testSynsetDefinition(): Unit = {
Console.println(">>> wn.synset('car.n.01').definition")
val sd = wn.definition(wn.synset("car", POS.NOUN, 1))
Console.println(sd)
Assert.assertTrue(sd.contains(";"))
}
/**
* >>> wn.synset('car.n.01').examples
* ['he needs a car to get to work']
*/
@Test
def testSynsetExamples(): Unit = {
Console.println(">>> wn.synset('car.n.01').examples")
val se = wn.examples(wn.synset("car", POS.NOUN, 1))
Console.println(se)
Assert.assertEquals(1, se.size)
}
/**
* >>> wn.synset('car.n.01').lemmas
* [Lemma('car.n.01.car'), Lemma('car.n.01.auto'), \
* Lemma('car.n.01.automobile'),\
* Lemma('car.n.01.machine'), Lemma('car.n.01.motorcar')]
* >>> wn.synset('car.n.01').lemmas[1]
* Lemma('car.n.01.auto')
*/
@Test
def testSynsetLemmas(): Unit = {
Console.println(">>> wn.synset('car.n.01').lemmas")
val sl = wn.lemmas(wn.synset("car", POS.NOUN, 1))
Console.println(sl.map(l => wn.format(l)))
Assert.assertEquals(5, sl.size)
Assert.assertTrue(sl(1).getLemma().equals("auto"))
}
/**
* >>> wn.lemma('car.n.01.automobile').name
* 'automobile'
*/
@Test
def testSynsetLemma(): Unit = {
Console.println(">>> wn.lemma('car.n.01.automobile').name")
val sl = wn.lemma(wn.synset("car", POS.NOUN, 1), 2)
sl match {
case Some(x) => {
Console.println(x.getLemma())
Assert.assertTrue("automobile".equals(x.getLemma()))
}
case None => Assert.fail()
}
}
/**
* >>> for synset in wn.synsets('car'):
* ... print synset.lemma_names
* ...
* ['car', 'auto', 'automobile', 'machine', 'motorcar']
* ['car', 'railcar', 'railway_car', 'railroad_car']
* ['car', 'gondola']
* ['car', 'elevator_car']
* ['cable_car', 'car']
*/
@Test
def testSynsetsAndLemmaNames(): Unit = {
Console.println(">>> for synset in wn.synsets('car'):")
Console.println("... print synset.lemma_names")
Console.println("...")
val lns = wn.synsets("car")
.map(ss => wn.lemmaNames(Some(ss)))
lns.foreach(ln =>
Console.println("[" + ln.mkString(", ") + "]"))
Assert.assertEquals(5, lns.size)
Assert.assertEquals(5, lns(0).size)
}
/**
* >>> wn.lemmas('car')
* [Lemma('car.n.01.car'), Lemma('car.n.02.car'), \
* Lemma('car.n.03.car'), Lemma('car.n.04.car'), \
* Lemma('cable_car.n.01.car')]
* :NOTE: in NLTK, the third field in Lemma indicates
* the (unique) sequence number of the synset from which
* the lemma is derived. For example, Lemma('car.n.01.car')
* comes from the first synset with word(0) == "car".
* JWNL does not capture the information, the index
* here means the sequence number of the lemma inside
* the synset.
*/
@Test
def testLemmas(): Unit = {
Console.println(">>> wn.lemmas('car')")
val ls = wn.lemmas("car")
Console.println(ls.map(l => wn.format(l)))
}
/**
* >>> motorcar = wn.synset('car.n.01')
* >>> types_of_motorcar = motorcar.hyponyms()
* >>> types_of_motorcar[26]
* Synset('ambulance.n.01')
* :NOTE: NLTK's wordnet returns hyponyms in a different
* order than JWNL but both return the same number of
* synsets. Test is modified accordingly.
*/
@Test
def testHyponyms(): Unit = {
Console.println(">>> motorcar = wn.synset('car.n.01')")
Console.println(">>> types_of_motorcar = motorcar.hyponyms()")
val motorcar = wn.synset("car", POS.NOUN, 1)
val typesOfMotorcar = wn.hyponyms(motorcar)
Console.println(">>> types_of_motorcar")
Console.println(typesOfMotorcar.map(ss => wn.format(ss)))
Assert.assertEquals(31, typesOfMotorcar.size)
Console.println(">>> types_of_motorcar[0]")
val ambulance = typesOfMotorcar(0)
Console.println(wn.format(ambulance))
Assert.assertEquals("ambulance.n.01", wn.format(ambulance))
Console.println(">>> sorted([lemma.name for synset\n" +
"... in types_of_motorcar for lemma in synset.lemmas])")
val sortedMotorcarNames = typesOfMotorcar
.map(ss => wn.lemmaNames(Some(ss))(0))
.sortWith((a,b) => a < b)
Console.println(sortedMotorcarNames)
Assert.assertEquals("Model_T", sortedMotorcarNames(0))
}
/**
* >>> motorcar.hypernyms()
* [Synset('motor_vehicle.n.01')]
*/
@Test
def testHypernyms(): Unit = {
Console.println(">> motorcar.hypernyms")
val motorcar = wn.synset("car", POS.NOUN, 1)
val parents = wn.hypernyms(motorcar)
Console.println(parents.map(p => wn.format(p)))
Assert.assertEquals(1, parents.size)
Assert.assertEquals("motor_vehicle.n.01",
wn.format(parents(0)))
}
/**
* >>> paths = motorcar.hypernym_paths()
* >>> len(paths)
* 2
* >>> [synset.name for synset in paths[0]]
* ['entity.n.01', 'physical_entity.n.01', 'object.n.01',
* 'whole.n.02', 'artifact.n.01', 'instrumentality.n.03',
* 'container.n.01', 'wheeled_vehicle.n.01',
* 'self-propelled_vehicle.n.01', 'motor_vehicle.n.01',
* 'car.n.01']
* >>> [synset.name for synset in paths[1]]
* ['entity.n.01', 'physical_entity.n.01', 'object.n.01',
* 'whole.n.02', 'artifact.n.01', 'instrumentality.n.03',
* 'conveyance.n.03', 'vehicle.n.01',
* 'wheeled_vehicle.n.01', 'self-propelled_vehicle.n.01',
* 'motor_vehicle.n.01', 'car.n.01']
* >>> motorcar.root_hypernyms()
* [Synset('entity.n.01')]
*/
@Test
def testHypernymPaths(): Unit = {
Console.println(">>> paths = motorcar.hypernym_paths()")
Console.println(">>> len(paths)")
val motorcar = wn.synset("car", POS.NOUN, 1)
val paths = wn.hypernymPaths(motorcar)
Console.println(paths.size)
Assert.assertEquals(2, paths.size)
Console.println(">>> [synset.name for synset in paths[0]]")
val paths0 = paths(0).map(ss => wn.format(ss))
Console.println(paths0)
Console.println(">>> [synset.name for synset in paths[1]]")
val paths1 = paths(1).map(ss => wn.format(ss))
Console.println(paths1)
Console.println(">>> motorcar.root_hypernyms()")
val rhns = wn.rootHypernyms(motorcar)
.map(rhn => wn.format(rhn))
Console.println(rhns)
}
/**
* >>> wn.synset('tree.n.01').part_meronyms()
* [Synset('burl.n.02'), Synset('crown.n.07'),
* Synset('stump.n.01'), Synset('trunk.n.01'),
* Synset('limb.n.02')]
* >>> wn.synset('tree.n.01').substance_meronyms()
* [Synset('heartwood.n.01'), Synset('sapwood.n.01')]
* >>> wn.synset('tree.n.01').member_holonyms()
* [Synset('forest.n.01')]
*/
@Test
def testMiscRelationMethods(): Unit = {
Console.println(">>> wn.synset('tree.n.01').part_meronyms()")
val tree = wn.synset("tree", POS.NOUN, 1)
val pn = wn.partMeronyms(tree)
Console.println(pn.map(ss => wn.format(ss)))
Assert.assertEquals(5, pn.size)
Console.println(">>> wn.synset('tree.n.01').substance_meronyms()")
val sn = wn.substanceMeronyms(tree)
Assert.assertEquals(2, sn.size)
Console.println(sn.map(ss => wn.format(ss)))
Console.println(">>> wn.synset('tree.n.01').member_holonyms()")
val mn = wn.memberHolonyms(tree)
Assert.assertEquals(1, mn.size)
Console.println(mn.map(ss => wn.format(ss)))
}
/**
* >>> for synset in wn.synsets('mint', wn.NOUN):
* ... print synset.name + ':', synset.definition
* ...
* batch.n.02: (often followed by `of') a large number or amount or extent
* mint.n.02: any north temperate plant of the genus Mentha with aromatic leaves and
* small mauve flowers
* mint.n.03: any member of the mint family of plants
* mint.n.04: the leaves of a mint plant used fresh or candied
* mint.n.05: a candy that is flavored with a mint oil
* mint.n.06: a plant where money is coined by authority of the government
* >>> wn.synset('mint.n.04').part_holonyms()
* [Synset('mint.n.02')]
* >>> [x.definition for x
* ... in wn.synset('mint.n.04').part_holonyms()]
* ['any north temperate plant of the genus Mentha with
* aromatic leaves and small mauve flowers']
* >>> wn.synset('mint.n.04').substance_holonyms()
* [Synset('mint.n.05')]
* >>> [x.definition for x
* ... in wn.synset('mint.n.04').substance_holonyms()]
* ['a candy that is flavored with a mint oil']
*/
@Test
def testListSynsetNameDefinition(): Unit = {
val mintss = wn.synsets("mint", POS.NOUN)
Assert.assertEquals(6, mintss.size)
Console.println(">>> for synset in wn.synsets('mint', wn.NOUN):")
Console.println("... print synset.name + ':', synset.definition")
Console.println("...")
mintss.foreach(ss =>
Console.println(wn.format(ss) + ": " +
wn.definition(Some(ss))))
Console.println(">>> wn.synset('mint.n.04').part_holonyms()")
val mint = wn.synset("mint", POS.NOUN, 4)
val ph = wn.partHolonyms(mint)
Console.println(ph.map(ss => wn.format(ss)))
Console.println(">>> [x.definition for x")
Console.println("... in wn.synset('mint.n.04').part_holonyms()]")
Console.println(ph.map(ss => wn.definition(Some(ss))))
Console.println(">>> wn.synset('mint.n.04').substance_holonyms()")
val sh = wn.substanceHolonyms(mint)
Console.println(sh.map(ss => wn.format(ss)))
Console.println(">>> [x.definition for x")
Console.println("... in wn.synset('mint.n.04').substance_holonyms()]")
Console.println(sh.map(ss => wn.definition(Some(ss))))
}
/**
* >>> wn.synset('walk.v.01').entailments()
* [Synset('step.v.01')]
* >>> wn.synset('eat.v.01').entailments()
* [Synset('swallow.v.01'), Synset('chew.v.01')]
* >>> wn.synset('tease.v.03').entailments()
* [Synset('arouse.v.07'), Synset('disappoint.v.01')]
*/
@Test
def testVerbRelationships(): Unit = {
Console.println(">>> wn.synset('walk.v.01').entailments()")
val walk = wn.synset("walk", POS.VERB, 1)
val walkEnt = wn.entailments(walk)
Console.println(walkEnt.map(ss => wn.format(ss)))
Assert.assertEquals(1, walkEnt.size)
Console.println(">>> wn.synset('eat.v.01').entailments()")
val eat = wn.synset("eat", POS.VERB, 1)
val eatEnt = wn.entailments(eat)
Console.println(eatEnt.map(ss => wn.format(ss)))
Assert.assertEquals(2, eatEnt.size)
Console.println(">>> wn.synset('tease.v.03').entailments()")
val tease = wn.synset("tease", POS.VERB, 3)
val teaseEnt = wn.entailments(tease)
Console.println(teaseEnt.map(ss => wn.format(ss)))
Assert.assertEquals(2, teaseEnt.size)
}
/**
* >>> wn.lemma('supply.n.02.supply').antonyms()
* [Lemma('demand.n.02.demand')]
* >>> wn.lemma('rush.v.01.rush').antonyms()
* [Lemma('linger.v.04.linger')]
* >>> wn.lemma('horizontal.a.01.horizontal').antonyms()
* [Lemma('vertical.a.01.vertical'),
* Lemma('inclined.a.02.inclined')]
* >>> wn.lemma('staccato.r.01.staccato').antonyms()
* [Lemma('legato.r.01.legato')]
*/
@Test
def testLemmaAntonyms(): Unit = {
Console.println(">>> wn.lemma('supply.n.02.supply').antonyms()")
val supply = wn.lemma(wn.synset("supply", POS.NOUN, 2), "supply")
val supplyAntonyms = wn.antonyms(supply)
Console.println(supplyAntonyms.map(w => wn.format(w)))
Assert.assertEquals(1, supplyAntonyms.size)
Console.println(">>> wn.lemma('rush.v.01.rush').antonyms()")
val rush = wn.lemma(wn.synset("rush", POS.VERB, 1), "rush")
val rushAntonyms = wn.antonyms(rush)
Console.println(rushAntonyms.map(w => wn.format(w)))
Assert.assertEquals(1, rushAntonyms.size)
Console.println(">>> wn.lemma('horizontal.a.01.horizontal').antonyms()")
val horizontal = wn.lemma(wn.synset("horizontal", POS.ADJECTIVE, 1), "horizontal")
val horizontalAntonyms = wn.antonyms(horizontal)
Console.println(horizontalAntonyms.map(w => wn.format(w)))
Assert.assertEquals(2, horizontalAntonyms.size)
Console.println(">>> wn.lemma('staccato.r.01.staccato').antonyms()")
val staccato = wn.lemma(wn.synset("staccato", POS.ADVERB, 1), "staccato")
val staccatoAntonyms = wn.antonyms(staccato)
Console.println(staccatoAntonyms.map(w => wn.format(w)))
Assert.assertEquals(1, staccatoAntonyms.size)
}
/**
* >>> right = wn.synset('right_whale.n.01')
* >>> orca = wn.synset('orca.n.01')
* >>> minke = wn.synset('minke_whale.n.01')
* >>> tortoise = wn.synset('tortoise.n.01')
* >>> novel = wn.synset('novel.n.01')
* >>> right.lowest_common_hypernyms(minke)
* [Synset('baleen_whale.n.01')]
* >>> right.lowest_common_hypernyms(orca)
* [Synset('whale.n.02')]
* >>> right.lowest_common_hypernyms(tortoise)
* [Synset('vertebrate.n.01')]
* >>> right.lowest_common_hypernyms(novel)
* [Synset('entity.n.01')]
*/
@Test
def testSynsetLowestCommonHypernyms(): Unit = {
Console.println(">>> right = wn.synset('right_whale.n.01')")
Console.println(">>> orca = wn.synset('orca.n.01')")
Console.println(">>> minke = wn.synset('minke_whale.n.01')")
Console.println(">>> tortoise = wn.synset('tortoise.n.01')")
Console.println(">>> novel = wn.synset('novel.n.01')")
val right = wn.synset("right_whale", POS.NOUN, 1)
val orca = wn.synset("orca", POS.NOUN, 1)
val minke = wn.synset("minke_whale", POS.NOUN, 1)
val tortoise = wn.synset("tortoise", POS.NOUN, 1)
val novel = wn.synset("novel", POS.NOUN, 1)
Console.println(">>> right.lowest_common_hypernyms(minke)")
val rightMinkeLCH = wn.lowestCommonHypernym(right, minke)
Console.println(rightMinkeLCH.map(ss => wn.format(ss)))
Console.println(">>> right.lowest_common_hypernyms(orca)")
val rightOrcaLCH = wn.lowestCommonHypernym(right, orca)
Console.println(rightOrcaLCH.map(ss => wn.format(ss)))
Console.println(">>> right.lowest_common_hypernyms(tortoise)")
val rightTortoiseLCH = wn.lowestCommonHypernym(right, tortoise)
Console.println(rightTortoiseLCH.map(ss => wn.format(ss)))
Console.println(">>> right.lowest_common_hypernyms(novel)")
val rightNovelLCH = wn.lowestCommonHypernym(right, novel)
Console.println(rightNovelLCH.map(ss => wn.format(ss)))
}
/**
* >>> wn.synset('baleen_whale.n.01').min_depth()
* 14
* >>> wn.synset('whale.n.02').min_depth()
* 13
* >>> wn.synset('vertebrate.n.01').min_depth()
* 8
* >>> wn.synset('entity.n.01').min_depth()
* 0
*/
@Test
def testSynsetMinDepth(): Unit = {
Console.println(">>> wn.synset('baleen_whale.n.01').min_depth()")
val baleenWhaleMinDepth = wn.minDepth(wn.synset("baleen_whale", POS.NOUN, 1))
Console.println(baleenWhaleMinDepth)
Assert.assertEquals(14, baleenWhaleMinDepth)
Console.println(">>> wn.synset('whale.n.02').min_depth()")
val whaleMinDepth = wn.minDepth(wn.synset("whale", POS.NOUN, 2))
Console.println(whaleMinDepth)
Assert.assertEquals(13, whaleMinDepth)
Console.println(">>> wn.synset('vertebrate.n.01').min_depth()")
val vertebrateMinDepth = wn.minDepth(wn.synset("vertebrate", POS.NOUN, 1))
Console.println(vertebrateMinDepth)
Assert.assertEquals(8, vertebrateMinDepth)
Console.println(">>> wn.synset('entity.n.01').min_depth()")
val entityMinDepth = wn.minDepth(wn.synset("entity", POS.NOUN, 1))
Console.println(entityMinDepth)
Assert.assertEquals(0, entityMinDepth)
}
/**
* >>> right.path_similarity(minke)
* 0.25
* >>> right.path_similarity(orca)
* 0.16666666666666666
* >>> right.path_similarity(tortoise)
* 0.076923076923076927
* >>> right.path_similarity(novel)
* 0.043478260869565216
*/
@Test
def testPathSimilarity(): Unit = {
val right = wn.synset("right_whale", POS.NOUN, 1)
val orca = wn.synset("orca", POS.NOUN, 1)
val minke = wn.synset("minke_whale", POS.NOUN, 1)
val tortoise = wn.synset("tortoise", POS.NOUN, 1)
val novel = wn.synset("novel", POS.NOUN, 1)
Console.println(">>> right.path_similarity(minke)")
val rightMinkePathSimilarity = wn.pathSimilarity(right, minke)
Console.println(rightMinkePathSimilarity)
Assert.assertEquals(0.25D, rightMinkePathSimilarity, 0.01D)
Console.println(">>> right.path_similarity(orca)")
val rightOrcaPathSimilarity = wn.pathSimilarity(right, orca)
Console.println(rightOrcaPathSimilarity)
Assert.assertEquals(0.1667D, rightOrcaPathSimilarity, 0.01D)
Console.println(">>> right.path_similarity(tortoise)")
val rightTortoisePathSimilarity = wn.pathSimilarity(right, tortoise)
Console.println(rightTortoisePathSimilarity)
Assert.assertEquals(0.0769D, rightTortoisePathSimilarity, 0.01D)
Console.println(">>> right.path_similarity(novel)")
val rightNovelPathSimilarity = wn.pathSimilarity(right, novel)
Console.println(rightNovelPathSimilarity)
Assert.assertEquals(0.043D, rightNovelPathSimilarity, 0.01D)
}
/**
* >>> dog = wn.synset('dog.n.01')
* >>> cat = wn.synset('cat.n.01')
* >>> hit = wn.synset('hit.v.01')
* >>> slap = wn.synset('slap.v.01')
* >>> dog.path_similarity(cat)
* 0.2...
* >>> hit.path_similarity(slap)
* 0.142...
* >>> dog.lch_similarity(cat)
* 2.028...
* >>> hit.lch_similarity(slap)
* 1.312...
* >>> dog.wup_similarity(cat)
* 0.857...
* >>> hit.wup_similarity(slap)
* 0.25
* >>> dog.res_similarity(cat, semcor_ic)
* 7.911...
* >>> dog.jcn_similarity(cat, semcor_ic)
* 0.449...
* >>> dog.lin_similarity(cat, semcor_ic)
* 0.886...
*/
@Test
def testOtherSimilarities(): Unit = {
Console.println(">>> dog = wn.synset('dog.n.01')")
Console.println(">>> cat = wn.synset('cat.n.01')")
Console.println(">>> hit = wn.synset('hit.v.01')")
Console.println(">>> slap = wn.synset('slap.v.01')")
val dog = wn.synset("dog", POS.NOUN, 1)
val cat = wn.synset("cat", POS.NOUN, 1)
val hit = wn.synset("hit", POS.VERB, 1)
val slap = wn.synset("slap", POS.VERB, 1)
Console.println(">>> dog.path_similarity(cat)")
val dogCatPathSimilarity = wn.pathSimilarity(dog, cat)
Console.println(dogCatPathSimilarity)
Console.println(">>> hit.path_similarity(slap)")
val hitSlapPathSimilarity = wn.pathSimilarity(hit, slap)
Console.println(hitSlapPathSimilarity)
Assert.assertEquals(0.2D, dogCatPathSimilarity, 0.01D)
Assert.assertEquals(0.1428D, hitSlapPathSimilarity, 0.01D)
Console.println(">>> dog.lch_similarity(cat)")
val dogCatLchSimilarity = wn.lchSimilarity(dog, cat)
Console.println(dogCatLchSimilarity)
Console.println(">>> hit.lch_similarity(slap)")
val hitSlapLchSimilarity = wn.lchSimilarity(hit, slap)
Console.println(hitSlapLchSimilarity)
Assert.assertEquals(2.079D, dogCatLchSimilarity, 0.01D)
Assert.assertEquals(1.386D, hitSlapLchSimilarity, 0.01D)
Console.println(">>> dog.wup_similarity(cat)")
val dogCatWupSimilarity = wn.wupSimilarity(dog, cat)
Console.println(dogCatWupSimilarity)
Console.println(">>> hit.wup_similarity(slap)")
val hitSlapWupSimilarity = wn.wupSimilarity(hit, slap)
Console.println(hitSlapWupSimilarity)
Assert.assertEquals(0.866D, dogCatWupSimilarity, 0.01D)
Assert.assertEquals(0.25D, hitSlapWupSimilarity, 0.01D)
Console.println(">>> dog.res_similarity(cat)")
val dogCatResSimilarity = wn.resSimilarity(dog, cat)
Console.println(dogCatResSimilarity)
Console.println(">>> hit.res_similarity(slap)")
Assert.assertEquals(7.254D, dogCatResSimilarity, 0.01D)
Console.println(">>> dog.jcn_similarity(cat)")
val dogCatJcnSimilarity = wn.jcnSimilarity(dog, cat)
Console.println(dogCatJcnSimilarity)
Assert.assertEquals(0.537D, dogCatJcnSimilarity, 0.01D)
Console.println(">>> dog.lin_similarity(cat)")
val dogCatLinSimilarity = wn.linSimilarity(dog, cat)
Console.println(dogCatLinSimilarity)
Assert.assertEquals(0.886D, dogCatLinSimilarity, 0.01D)
}
/**
* >>> for synset in list(wn.all_synsets('n'))[:10]:
* ... print(synset)
* ...
* Synset('entity.n.01')
* Synset('physical_entity.n.01')
* Synset('abstraction.n.06')
* Synset('thing.n.12')
* Synset('object.n.01')
* Synset('whole.n.02')
* Synset('congener.n.03')
* Synset('living_thing.n.01')
* Synset('organism.n.01')
* Synset('benthos.n.02')
* :NOTE: order of synsets returned is different in
* JWNL than with NLTK.
*/
@Test
def testAllSynsets(): Unit = {
Console.println(">>> for synset in list(wn.all_synsets('n'))[:10]:")
Console.println("... print(synset)")
Console.println("...")
val fss = wn.allSynsets(POS.NOUN)
.take(10)
.toList
fss.foreach(ss => Console.println(wn.format(ss)))
Assert.assertEquals(10, fss.size)
}
/**
* >>> print(wn.morphy('denied', wn.VERB))
* deny
* >>> print(wn.morphy('dogs'))
* dog
* >>> print(wn.morphy('churches'))
* church
* >>> print(wn.morphy('aardwolves'))
* aardwolf
* >>> print(wn.morphy('abaci'))
* abacus
* >>> print(wn.morphy('book', wn.NOUN))
* book
* >>> wn.morphy('hardrock', wn.ADV)
* >>> wn.morphy('book', wn.ADJ)
* >>> wn.morphy('his', wn.NOUN)
*/
@Test
def testMorphy(): Unit = {
Console.println(">>> print(wn.morphy('denied', wn.VERB))")
val denied = wn.morphy("denied", POS.VERB)
Console.println(denied)
Assert.assertEquals("deny", denied)
Console.println(">>> print(wn.morphy('dogs'))")
val dogs = wn.morphy("dogs")
Console.println(dogs)
Assert.assertEquals("dog", dogs)
Console.println(">>> print(wn.morphy('churches'))")
val churches = wn.morphy("churches")
Console.println(churches)
Assert.assertEquals("church", churches)
Console.println(">>> print(wn.morphy('aardwolves'))")
val aardwolves = wn.morphy("aardwolves")
Console.println(aardwolves)
Assert.assertEquals("aardwolf", aardwolves)
Console.println(">>> print(wn.morphy('abaci'))")
val abaci = wn.morphy("abaci")
Console.println(abaci)
Assert.assertEquals("abacus", abaci)
Console.println(">>> print(wn.morphy('book', wn.NOUN))")
val book = wn.morphy("book", POS.NOUN)
Console.println(book)
Assert.assertEquals("book", book)
Console.println(">>> wn.morphy('hardrock', wn.ADV)")
val hardrock = wn.morphy("hardrock", POS.ADVERB)
Console.println(hardrock)
Assert.assertTrue(hardrock.isEmpty)
Console.println(">>> wn.morphy('book', wn.ADJ)")
val bookAdj = wn.morphy("book", POS.ADJECTIVE)
Console.println(bookAdj)
Assert.assertTrue(bookAdj.isEmpty)
Console.println(">>> wn.morphy('his', wn.NOUN)")
val his = wn.morphy("his", POS.NOUN)
Console.println(his)
Assert.assertTrue(his.isEmpty)
}
}
|
Writing this code to mimic the functionality of NLTK's Wordnet interface has given me quite a bit of insight into JWNL (and to a lesser extent WS4j). In the past I had used hyponyms and hypernyms, but there are a large number of other relationships available. The other new thing I learned was the Wordnet Morphological Analyzer, an English Lemmatizer, which is available in JWNL, and with which I implemented the wn.morphy() methods. In terms of utility, I now have a way of accessing Wordnet from Scala that is as powerful as NLTK's.
5 comments (moderated to prevent spam):
Hi, thanks for the code. Your lesk similarity is not working, would you please test it, it would be nice if you put your code on github, so everybody can use it.
You are welcome and thanks for pointing out the issue. I added a call to find Lesk similarity between "car" and "bus" and am getting 6.0. Unfortunately it appears that Lesk similarity is not implemented in NLTK so could not verify the result. From the ws4j code which I am calling out to from my code, it looks like it implements the extended Lesk measure which looks not only at overlap between glosses of the individual synsets but their parents as well, so 6.0 seems reasonable. So perhaps when you said "not working" it meant no example? If not can you please provide more details.
Regarding putting on github, my code is currently hosted on bitbucket in a private repo, because I had initially thought of giving this to my employer, but that may not be required anymore, so I may open it up, not sure, still thinking about it.
Thanks for reply, here is the website that I check the answers, it use the same code that you are using (wsj4): http://ws4jdemo.appspot.com/
here is my example: weak (adjective, 1st sense) and physical(adjective, 1st sense) I get diffrent number from the website.
Thanks, looks like even the lesk_similarity(car, bus) I calculated (6) is low compared to what the demo page shows (615). I am guessing it uses a different algorithm or there is a bug in my code where I invoke Lesk (edu.cmu.lti.ws4j.impl.Lesk). Let me check and get back.
Hi Omid, looks like the two have slightly differing algorithms, and even different ideas about the overlap scoring. For one ws4j normalizes the Lesk score by default, which I turned off by overriding its packaged similarity.conf with a local one. Even so, the comparisons being made are different, ws4j makes 14 comparisons against 19 for ws4jdemo. Here is a trace for lesk("car", "bus") from both, notice that individual scores for the same test differ as well.
Trace from ws4j:
Functions: - : 1.0
Functions: - hypo : 1.0
Functions: - mero : 4.0
Functions: - holo : 1.0
Functions: hype - : 1.0
Functions: hype - mero : 1.0
Functions: hypo - : 1.0
Functions: hypo - hype : 1.0
Functions: hypo - hypo : 1.0
Functions: hypo - mero : 1.0
Functions: mero - : 2.0
Functions: mero - hypo : 1.0
Functions: mero - mero : 169.0
Functions: mero - holo : 1.0
Trace from ws4jdemo:
Functions: example - example : 5
Functions: example - glos : 1
Functions: glos - glos : 2
Functions: glos - holo gloss : 1
Functions: glos - hypo gloss : 4
Functions: glos - mero gloss : 10
Functions: hype gloss - glos : 2
Functions: hype gloss - hypo gloss : 2
Functions: hype gloss - mero gloss : 6
Functions: hypo gloss - glos : 7
Functions: hypo gloss - holo gloss : 3
Functions: hypo gloss - hype gloss : 4
Functions: hypo gloss - hypo gloss : 15
Functions: hypo gloss - mero gloss : 19
Functions: mero gloss - glos : 6
Functions: mero gloss - holo gloss : 3
Functions: mero gloss - hype gloss : 3
Functions: mero gloss - hypo gloss : 17
Functions: mero gloss - mero gloss : 505
The discrepancy seems to be noted by others as well, there is open issue for WUP similarity along the same lines.
I guess as long as it is consistent within an application, it shouldn't matter too much, although I would like to see this fixed also...
Post a Comment