使用R Wordnet包获取反义词

使用R Wordnet包获取反义词,r,wordnet,R,Wordnet,我正在尝试使用wordnet软件包获取单词的反义词。这对某些词有效,但对其他词却返回一个错误。该函数基本上只是封装在函数中的包文档中的使用示例 # The function: antonyms <- function(x){ filter <- getTermFilter("ExactMatchFilter", x, TRUE) terms <- getIndexTerms("ADJECTIVE", 5, filter) synsets <- getSyns

我正在尝试使用wordnet软件包获取单词的反义词。这对某些词有效,但对其他词却返回一个错误。该函数基本上只是封装在函数中的包文档中的使用示例

# 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. 
#功能:
反义词你的问题是great没有直接的反义词。如果你这样做,你会发现所有的反义词都是通过其他单词间接表达的。你必须先检查一下类似的关系,然后在那里查找反义词。相反,(反对)

您可能希望使用
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))
}

反义词非常感谢!如果我进一步完善这个函数,我会发帖,但这肯定是一个很好的开始。