我有兴趣根据由两列数据框组成的字典替换tm Corpus对象中的所有单词,其中第一列是要匹配的单词,第二列是替换单词。

我被translate函数所困扰。我看到了this answer,但无法将其转换为要传递给tm_map的函数。

请考虑以下MWE

library(tm)

docs <- c("first text", "second text")
corp <- Corpus(VectorSource(docs))

dictionary <- data.frame(word = c('first', 'second', 'text'),
                      translation = c('primo', 'secondo', 'testo'))

translate <- function(text, dictionary) {
  # Would like to replace each word of text with corresponding word in dictionary
}

corp_translated <- tm_map (corp, translate)

inspect(corp_translated)

# Expected result

# A corpus with 2 text documents
#
# The metadata consists of 2 tag-value pairs and a data frame
# Available tags are:
#   create_date creator
# Available variables in the data frame are:
#   MetaID

# [[1]]
# primo testo

# [[2]]
# secondo testo

最佳答案

我建议不要为字典使用data.frame,因为R中的基本对象( vector )默认情况下是字典。

      dict  <- c('primo', 'secondo', 'testo')
names(dict) <- c('first', 'second', 'text')

然后到"tanslate" x,其中x可能是"second",您只需使用:
   dict[[x]]

您甚至不需要包装函数。

如果要以相反的方向平移,请使用
   name(dict)[names(dict) %in% x]

或者你可以翻字典
         dict.flip  <- names(dict)
   names(dict.flip) <- dict

关于r - 根据词典数据框替换语料库中的单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20580002/

10-12 16:49
查看更多