【问题标题】:Removing words featured in character vector from string从字符串中删除字符向量中的单词
【发布时间】:2019-05-03 05:43:53
【问题描述】:

我在 R 中有一个停用词的字符向量:

stopwords = c("a" ,
            "able" ,
            "about" ,
            "above" ,
            "abst" ,
            "accordance" ,
            ...
            "yourself" ,
            "yourselves" ,
            "you've" ,
            "z" ,
            "zero")

假设我有字符串:

str <- c("I have zero a accordance")

如何从str 中删除我定义的停用词?

我认为gsub 或其他grep 工具可能是实现此目标的不错选择,尽管欢迎其他建议。

【问题讨论】:

  • 你可以试试gsub(paste(stopwords, collapse="|"), "", str)
  • @akrun 最好gsub(paste0("\\b(",paste(stopwords, collapse="|"),")\\b"), "", str),否则每个a 都会被删除。
  • @nicola 是的,这样更好。我之前没有测试过。

标签: r


【解决方案1】:

试试这个:

str <- c("I have zero a accordance")

stopwords = c("a", "able", "about", "above", "abst", "accordance", "yourself",
"yourselves", "you've", "z", "zero")

x <- unlist(strsplit(str, " "))

x <- x[!x %in% stopwords]

paste(x, collapse = " ")

# [1] "I have"

补充:编写“removeWords”函数很简单,因此无需为此加载外部包:

removeWords <- function(str, stopwords) {
  x <- unlist(strsplit(str, " "))
  paste(x[!x %in% stopwords], collapse = " ")
}

removeWords(str, stopwords)
# [1] "I have"

【讨论】:

  • 我发现这种方式比 tm 包中实现的功能更好,因为后者有大小限制。我使用论坛 cmets 语料库并希望从文本中删除所有用户名(大约 70000)。我不断收到 R 的错误,因为正则表达式太大。谢谢!
  • 这个解决方案比tmpackage 快得多!谢谢分享!!
【解决方案2】:

您可以为此使用tm 库:

require("tm")
removeWords(str,stopwords)
#[1] "I have   "

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多