I'm trying to get antonyms of words using the wordnet package. This works for some words while returning an error I don't really get for others. The function is basically just the usage example from the package documentation encapsulated in a function.
# The function:
antonyms <- function(x){
filter <- getTermFilter("ExactMatchFilter", x, TRUE)
terms <- getIndexTerms("ADJECTIVE", 5, filter)
synsets <- getSynsets(terms[[1]])
related <- getRelatedSynsets(synsets[[1]], "!")
sapply(related, getWord)
}
# Some words work while others return an error:
> antonyms("happy")
[1] "unhappy"
> antonyms("great")
Error in .jcall(l, "Ljava/util/Iterator;", "iterator") :
RcallMethod: invalid object parameter
# The Error is caused by the "related" step.
My goal here is to have a function that I can lapply vectors of words to in order to get their antonyms as output, much like the synonyms function provided by the package.
Thanks for any ideas :)
edit: I'm on: OSX 10.8.5, wordnet package (in R) wordnet_0.1-9 and wordnet 3.0_3 (system wide through macports), rJava 0.9-4, R version 3.0.1 (2013-05-16).
Your problem is that great doesn't have direct antonyms. If you look up great in WordNet Search, you will see that all antonyms are indirect via some other word. You'd have to first go over the similar to relationships, and look up for antonyms there. On the contrary, happy has a direct antonym (opposed to).
You might want to catch this specific error with a tryCatch
:
antonyms <- function(x){
filter <- getTermFilter("ExactMatchFilter", x, TRUE)
terms <- getIndexTerms("ADJECTIVE", 5, filter)
synsets <- getSynsets(terms[[1]])
related <- tryCatch(
getRelatedSynsets(synsets[[1]], "!"),
error = function(condition) {
message("No direct antonym found")
if (condition$message == "RcallMethod: invalid object parameter")
message("No direct antonym found")
else
stop(condition)
return(NULL)
}
)
if (is.null(related))
return(NULL)
return(sapply(related, getWord))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With