【问题标题】:Replace words in corpus according to dictionary data frame根据字典数据框替换语料库中的单词
【发布时间】:2014-01-02 00:26:58
【问题描述】:

我有兴趣根据由两列数据框组成的字典替换 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

【问题讨论】:

    标签: r nlp tm


    【解决方案1】:

    我建议不要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
    

    【讨论】:

    • 抱歉,我不明白如何操作 dict[[x]]。假设我有一个字符串str = "First Second Text" 我应该如何用dict[[x]] 翻译它?
    • 我认为他们需要gsub
    • 如果您还没有将文本拆分为单个单词,您需要先这样做:TEXT.split &lt;- strsplit(TEXT, "\\s") 如果您没有所有单词的翻译,那么您需要某种形式的逻辑。使用ifelse(慢)或match%in%
    【解决方案2】:

    结合tm 包的tm_map 函数,您可以使用stringi 包中的stri_replace_all_fixed。例如:

    library(tm)
    library(stringi)
    
    docs <- c("first text", "second text")
    corp <- Corpus(VectorSource(docs))
    
    word <- c('first', 'second', 'text')
    tran <- c('primo', 'secondo', 'testo')
    
    corp <- tm_map(corp, function(x) stri_replace_all_fixed(x, word, tran, vectorize_all = FALSE))
    

    【讨论】:

      猜你喜欢
      • 2018-06-12
      • 2018-07-27
      • 2013-11-29
      • 2020-12-27
      • 2015-10-30
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      相关资源
      最近更新 更多