问题描述
在 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)),]
解决方法
既然你使用了数据框,你可以试试这个:
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)
,
您可以将句子拆分为单词,仅保留属于您字典的单词,然后再将它们粘贴到一个句子中。
DF1$Text1 <- sapply(strsplit(DF1$Text,'\\s+'),function(x)
paste0(Filter(english.words,x),collapse = ' '))
这里我创建了一个名为 Text1
的新列,只有英文单词,如果您想替换原来的列,您可以将输出保存在 DF1$Text
中。