【问题标题】:Replace a list of words occuring in sentences in R [duplicate]替换R中句子中出现的单词列表[重复]
【发布时间】:2017-01-04 12:02:38
【问题描述】:

我有一个数据框,其中有一列中的句子列表。现在我有一个单词列表和另一个替换单词列表,如下所示。

DF

Date       Sentences
9-Nov-16   nah, i got rid of them overyears ago i was only watching pbs by then anyway i have xfinity on demand+netflix on my 'puter
9-Nov-16   Omg Netflix is working on my Xfinity!

等等

单词列表

words <- c("nah","'puter","Omg")
trans <- c("No","computer","Oh my God")

等等。

现在我想将上述数据框中的句子中的“Nah”替换为“No”,将“'puter”替换为“computer”,“Omg”替换为“Oh my God”等等。为此,我使用以下代码。

DF$Sentences<- str_replace_all( DF$Sentences, paste0("\\b",words,"\\b"), trans)

但这并不能替换句子中的单词。有人能告诉我这样做的正确方法吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以从qdap使用mgsub

    library(qdap)
    DF$Sentences <- mgsub(words, trans, DF$Sentences)
    

    或在for 循环中使用gsub

    for(j in seq_along(words)){
      DF$Sentences <- gsub(words[j], trans[j], DF$Sentences)
    }
    

    【讨论】:

      【解决方案2】:

      您可以将stri_replace_all_fixedstringi 中的vectorize_all=FALSEvectorize_all=FALSE 一起使用,例如

      stri_replace_all_fixed(DF[["Sentences"]], words,  trans, vectorize_all=FALSE)
      

      【讨论】:

        猜你喜欢
        • 2020-05-23
        • 1970-01-01
        • 2021-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多