【问题标题】:Removing words and symbols from text in R从R中的文本中删除单词和符号
【发布时间】:2021-01-04 09:31:00
【问题描述】:

考虑以下示例。可以从text 中删除stopwords 吗?

library(tm)
text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
stopwords <- ("≤µm", "≥°f", "±μgm")

【问题讨论】:

    标签: r text stringr tm


    【解决方案1】:

    首先,您的示例字符串中有一些错误。 text 缺少引号,stopwords 缺少括号前的 c

    text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
    stopwords <- c("≤µm", "≥°f", "±μgm")
    

    您可以使用 stringr 从字符串中删除停用词中的值,如下所示:

    library(stringr)
    str_replace_all(text, paste(stopwords, collapse = "|"), "")
    

    【讨论】:

      【解决方案2】:

      您可以尝试gsub,如下所示

      gsub(paste0(stopwords, collapse = "|"),"",text)
      

      【讨论】:

        【解决方案3】:

        由于您要进行文本挖掘,您可能希望将输入字符串转换为单词向量。如果是这样,您可以通过子集轻松删除停用词。

        library(stringr)
        text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
        stopwords <- c("≤µm", "≥°f", "±μgm")
        text <- unlist(str_split(text, " "))
        text[!(sapply(text, function (x) any(str_detect(stopwords, x))))]
        

        如果你的工作让你把你的话放在 data.frame 或类似的地方,那么还有另一种方法:

        library(dplyr)
        library(stringr)
        text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
        stopwords <- c("≤µm", "≥°f", "±μgm")
        text <- unlist(str_split(text, " "))
        data.frame(words = text) %>% anti_join(data.frame(words = stopwords))
        

        【讨论】:

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