如何从 R 中的文本列表中提取单词?
How do I extract words from a list in a text in R?
我想从我的观察中提取特定的词,如果这些词存在的话。
a = c("friend", "cat", "dog")
b = "my friend has a dog"
如果我使用类似
的东西
results <- str_extract_all(b,a)
我会得到一个包含 3 个词的列表,其中会说明每个词在 a 向量中的出现频率,包括那些不存在于 b 中的词。
我想要一个向量、一个列表或一个字符串,其中只包含(和所有)包含在 a 和 b 中的单词。
就像是
结果=(“朋友”,“狗”)
我该怎么办?
我们可以 paste
使用 str_c
将它们合并为一个字符串,现在它应该可以工作了
library(stringr)
str_extract_all(b, str_c(a, collapse="|"))[[1]]
#[1] "friend" "dog"
或通过 unlist
转换为 vector
unlist(str_extract_all(b, a))
#[1] "friend" "dog"
使用 regmatches
的基础 R 选项
> unlist(regmatches(b, gregexpr(paste0(a, collapse = "|"), b)))
[1] "friend" "dog"
或
> intersect(unlist(strsplit(b, "\W+")), a)
[1] "friend" "dog"
我想从我的观察中提取特定的词,如果这些词存在的话。
a = c("friend", "cat", "dog")
b = "my friend has a dog"
如果我使用类似
的东西results <- str_extract_all(b,a)
我会得到一个包含 3 个词的列表,其中会说明每个词在 a 向量中的出现频率,包括那些不存在于 b 中的词。
我想要一个向量、一个列表或一个字符串,其中只包含(和所有)包含在 a 和 b 中的单词。 就像是 结果=(“朋友”,“狗”)
我该怎么办?
我们可以 paste
使用 str_c
将它们合并为一个字符串,现在它应该可以工作了
library(stringr)
str_extract_all(b, str_c(a, collapse="|"))[[1]]
#[1] "friend" "dog"
或通过 unlist
vector
unlist(str_extract_all(b, a))
#[1] "friend" "dog"
使用 regmatches
> unlist(regmatches(b, gregexpr(paste0(a, collapse = "|"), b)))
[1] "friend" "dog"
或
> intersect(unlist(strsplit(b, "\W+")), a)
[1] "friend" "dog"