从 R 数据框列中删除停用词

时间:2020-12-21 23:55:55

标签: r text-mining

情况是这样的,最初的解决方案似乎很简单,但结果证明比我预期的要复杂。

我有一个包含三列的 R 数据框:一个 ID、一个包含文本(评论)的列和一个包含我想根据文本预测的数值的列。

我已经对 text 列进行了一些预处理,因此它没有标点符号,小写,并且准备好被标记化并转换为矩阵,以便我可以在其上训练模型。问题是我不知道如何从该文本中删除停用词。

这是我试图用 text2vec 包做的事情。一开始我打算在这个块之前去除停用词。但任何地方都可以。

library(text2vec)

test_data <- data.frame(review_id=c(1,2,3),
                        review=c('is a masterpiece a work of art',
                        'sporting some of the best writing and voice work',
                        'better in every possible way when compared'),
                         score=c(90, 100, 100))

tokens <- word_tokenizer(test_data$review)
document_term_matrix <- create_dtm(itoken(tokens), hash_vectorizer())
model_tfidf <- TfIdf$new()
document_term_matrix <- model_tfidf$fit_transform(document_term_matrix)

document_term_matrix <- as.matrix(document_term_matrix)

我希望评论栏是这样的:

review=c('masterpiec work art',
         'sporting best writing voice work',
         'better possible way compared')

2 个答案:

答案 0 :(得分:1)

您可以为此使用 tidytext 包:

library(tidytext)
library(dplyr)

test_data %>%
  unnest_tokens(review, review) %>%
  anti_join(stop_words, by= c("review" = "word"))

#    review_id      review score
#1.2         1 masterpiece    90
#1.6         1         art    90
#2           2    sporting   100
#2.5         2     writing   100
#2.7         2       voice   100
#3.6         3    compared   100

要将单词重新排成一行,您可以这样做:

test_data %>%
  unnest_tokens(review, review) %>%
  anti_join(stop_words, by= c("review" = "word")) %>%
  group_by(review_id, score) %>%
  summarise(review = paste0(review, collapse = ' '))

#  review_id score review                
#      <dbl> <dbl> <chr>                 
#1         1    90 masterpiece art       
#2         2   100 sporting writing voice
#3         3   100 compared              

答案 1 :(得分:0)

事实证明,我最终解决了自己的问题。

我创建了以下函数:

remove_words_from_text <- function(text) {
  text <- unlist(strsplit(text, " "))
  paste(text[!text %in% words_to_remove], collapse = " ")
}

并通过 lapply 调用它。

words_to_remove <- stop_words$word
test_data$review <- lapply(test_data$review, remove_words_from_text)

这里希望能帮助那些和我有同样问题的人。