簡體   English   中英

從 R 數據框列中刪除停用詞

[英]Removing stopwords from R data frame column

情況是這樣的,一開始的解決方案似乎很簡單,但結果卻比我預期的要復雜。

我有一個包含三列的 R 數據框:一個 ID,一個包含文本(評論)的列,以及一個包含我想根據文本預測的數值的列。

我已經對文本列進行了一些預處理,因此它沒有標點符號、小寫字母,並且可以進行標記化並轉換為矩陣,因此我可以在其上訓練 model。 問題是我不知道如何從該文本中刪除停用詞。

這是我嘗試對 text2vec package 執行的操作。我最初計划在此塊之前刪除停用詞。 但任何地方都可以。

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')

您可以為此使用tidytext package:

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              

事實證明,我最終解決了自己的問題。

我創建了以下 function:

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)

希望能幫到和我遇到同樣問題的人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM