根据字典数据框替换语料库中的单词

标签 r nlp tm

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

我被 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中的基本对象,向量,是字典默认情况下。

      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

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

相关文章:

R:apply()中的自定义函数

python - 最常见单词或短语的 FreqDist

r - 无法获取推文的纬度和经度值

在 R 中删除过于常见的单词(出现在 80% 以上的文档中)

r - 支持向量机预测错误

r - 如何在 R 中导出一个变量,显示在较早日期记录的具有相同值的观察值的数量?

css - Shiny - 更改文本(框)的大小、颜色和字体

python - 如何使用 nltk 正则表达式模式来提取特定的短语 block ?

python - gensim - Word2vec 继续训练现有模型 - AttributeError : 'Word2Vec' object has no attribute 'compute_loss'

r - 尝试从 DocumentTermMatrix 中删除单词以使用主题模型