r - 使用 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 个可能的单词要从每一行中提取。我不知道另一种使用方法,但我将拥有一个大的正则表达式这一事实会使事情变慢或正则表达式的大小无关紧要?我认为它不会在每一行中出现多个这些单词,但是如果每行中出现多个单词,有一种方法可以自动制作多列?
解决方案
我们可以使用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>
推荐阅读
- python - 在准备 Keras NN 时应用 StandardScaler() 时遇到问题
- sql-server - 如何根据同一节点中不同属性值的匹配来查找和更新 XML 文档中的节点属性值?
- c# - WPF MainWindow 在运行时与预期结果不同
- php - Phalcon 与 php7.0 和 php7.3
- python - 为什么python中列表的“总和”会变平?
- python - 如何使用带有预训练模型但缺少标签文件 (.pbtxt) 的 TensorFlow 对象检测模型动物园
- comparator - 具有链式比较运算符的语言
- android - 在 CSS 像素、iOS 点和 Android dp 之间转换
- python - 将两个数据框与重复的列结合起来
- sql - 我对此脚本的引用有问题