首页 > 解决方案 > 是否有通过自定义字典清理的 R 函数

问题描述

在清理 R 中的数据时,我想使用自定义字典(超过 400,000 个单词)。我已经将字典加载为一个大字符列表,我正在尝试使用它,以便我的数据(VCorpus)中的内容妥协只有我字典里的单词。
例如:

#[1] "never give up uouo cbbuk jeez"  

会成为

#[1*] "never give up"  

因为“never”、“give”和“up”这些词都在自定义词典中。我以前尝试过以下方法:

#Reading the custom dictionary as a function
    english.words  <- function(x) x %in% custom.dictionary
#Filtering based on words in the dictionary
    DF2 <- DF1[(english.words(DF1$Text)),]

但我的结果是一个单词的字符列表。有什么建议吗?

标签: rtext-miningdata-cleaningsentiment-analysis

解决方案


由于您使用数据框,您可以尝试以下操作:

library(tidyverse)
library(tidytext)

dat<-tibble(text="never give up uouo cbbuk jeez")
words_to_keep<-c("never","give","up")

keep_function<-function(data,words_to_keep){
 data %>%
  unnest_tokens(word, text) %>% 
  filter(word %in% words_to_keep) %>%
  nest(text=word) %>%
  mutate(text = map(text, unlist), 
         text = map_chr(text, paste, collapse = " "))
  }

keep_function(dat,words_to_keep)

推荐阅读