首页 > 解决方案 > 使用 dplyr 和 stringr 从文本中提取单词

问题描述

我正在尝试找到一种从数据集中的文本列中提取单词的有效方法。我正在使用的方法是

library(dplyr)
library(stringr)

Text = c("A little bird told me about the dog", "A pig in a poke", "As busy as a bee")
data = as.data.frame(Text)
keywords <- paste0(c("bird", "dog", "pig","wolf","cat", "bee", "turtle"), collapse = "|")
data %>% mutate(Word = str_extract(Text, keywords))

这只是一个例子,但我有超过 2000 个可能的单词要从每一行中提取。我不知道另一种使用方法,但我将拥有一个大的正则表达式这一事实会使事情变慢或正则表达式的大小无关紧要?我认为它不会在每一行中出现多个这些单词,但是如果每行中出现多个单词,有一种方法可以自动制作多列?

标签: rregexstringdplyr

解决方案


我们可以使用str_extract_all返回 a list,将list元素转换为命名列表或tibble使用unnest_wider

library(purrr)
library(stringr)
library(tidyr)
library(dplyr)
data %>% 
  mutate(Words = str_extract_all(Text, keywords),
        Words = map(Words, ~ as.list(unique(.x)) %>% 
                              set_names(str_c('col', seq_along(.))))) %>%
  unnest_wider(Words)
# A tibble: 3 x 3
#  Text                                col1  col2 
#  <fct>                               <chr> <chr>
#1 A little bird told me about the dog bird  dog  
#2 A pig in a poke                     pig   <NA> 
#3 As busy as a bee                    bee   <NA> 

推荐阅读