从字符串中删除字符向量中的单词

标签 r

我在 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工具可能是实现这一目标的一个很好的候选者,尽管欢迎其他建议。

最佳答案

尝试这个:

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"

关于从字符串中删除字符向量中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35790652/

相关文章:

r - 关闭 ggplot 中的一些图例

R:如何获得 2 个向量的唯一成对组合

r - 使用 lmer [R] 缩放多级回归的正确方法

r - 趋势线根据 ggplot2 中的轴比例变化

r - 对变量的所有离散值使用 dplyr 过滤器

删除绘制数据和轴之间的空间

r - 如何在 Mac 上安装多个版本的 R 而不会覆盖旧版本?

r - 有没有办法在 gt 包中用希腊符号重命名表列?

r - 如何在插入符号包中制作 TreeMap ?

c - 使用 C 函数获取不同 R 对象的类属性时不一致