scr*_*Owl 4 nlp r subset stop-words tm
我有一个包含字符串的数据框,我想从中删除停用词.我试图避免使用该tm包,因为它是一个大型数据集,tm似乎运行有点慢.我正在使用tm stopword字典.
library(plyr)
library(tm)
stopWords <- stopwords("en")
class(stopWords)
df1 <- data.frame(id = seq(1,5,1), string1 = NA)
head(df1)
df1$string1[1] <- "This string is a string."
df1$string1[2] <- "This string is a slightly longer string."
df1$string1[3] <- "This string is an even longer string."
df1$string1[4] <- "This string is a slightly shorter string."
df1$string1[5] <- "This string is the longest string of all the other strings."
head(df1)
df1$string1 <- tolower(df1$string1)
str1 <- strsplit(df1$string1[5], " ")
> !(str1 %in% stopWords)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
这不是我正在寻找的答案.我试图得到一个向量或字符串不在stopWords向量中.
我究竟做错了什么?
Aru*_*run 12
您没有正确访问列表,并且您没有从结果中获取元素%in%(它给出了逻辑向量为TRUE/FALSE).你应该做这样的事情:
unlist(str1)[!(unlist(str1) %in% stopWords)]
Run Code Online (Sandbox Code Playgroud)
(要么)
str1[[1]][!(str1[[1]] %in% stopWords)]
Run Code Online (Sandbox Code Playgroud)
对于整个data.framedf1,您可以执行以下操作:
'%nin%' <- Negate('%in%')
lapply(df1[,2], function(x) {
t <- unlist(strsplit(x, " "))
t[t %nin% stopWords]
})
# [[1]]
# [1] "string" "string."
#
# [[2]]
# [1] "string" "slightly" "string."
#
# [[3]]
# [1] "string" "string."
#
# [[4]]
# [1] "string" "slightly" "shorter" "string."
#
# [[5]]
# [1] "string" "string" "strings."
Run Code Online (Sandbox Code Playgroud)
第一的。您应该取消列出str1或使用lapplyif str1is vector:
!(unlist(str1) %in% words)
#> [1] TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE
Run Code Online (Sandbox Code Playgroud)
第二。复杂的解决方案:
string <- c("This string is a string.",
"This string is a slightly longer string.",
"This string is an even longer string.",
"This string is a slightly shorter string.",
"This string is the longest string of all the other strings.")
rm_words <- function(string, words) {
stopifnot(is.character(string), is.character(words))
spltted <- strsplit(string, " ", fixed = TRUE) # fixed = TRUE for speedup
vapply(spltted, function(x) paste(x[!tolower(x) %in% words], collapse = " "), character(1))
}
rm_words(string, tm::stopwords("en"))
#> [1] "string string." "string slightly longer string." "string even longer string."
#> [4] "string slightly shorter string." "string longest string strings."
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13356 次 |
| 最近记录: |