首页 > 解决方案 > 如何在保留数据框的同时仅提取与单词条件匹配的句子

问题描述

下面的代码部分很好地代表了我正在处理的数据集。

x <- "test is bad. test1 is good. but test is better. Yet test1 is fake"
y <- "test1 is bad. test is good. but test1 is better. Yet test is fake"
a <- "this sentence is for trying purposes"
z <- data.frame(text = c(x,y,a))
z$date <- c("2011","2012","2015")
z$amount <- c(20000, 300, 5600)
z$text <- as.character(z$text)

我想要做的基本上是只提取包含单词 test1 的句子并将它们解析到一个新列(z$sentences)中以进行其他操作。

我尝试过使用以下内容:

z$sentences <- grep("test1", unlist(strsplit(z$text, '(?<=\\.)\\s+', 
                              perl=TRUE)), value=TRUE)

但它返回一个错误,因为替换有 4 行,而数据有 3。

我也尝试过使用 unlist,但遗憾的是,其他列信息在此过程中丢失了。

2个结果是令人满意的:

仅包含“test1”或长格式的句子的额外列,每行仍包含带有句子的数据(日期,金额)。

预期输出:

与列中匹配的所有句子

与列中匹配的所有句子

每个句子匹配条件都有一个新行

与条件匹配的每个句子都有一个新行,尽管最后一行不必存在。

欢迎任何帮助

标签: r

解决方案


问题是grep只返回match可能小于原始长度的元素

lst1 <- strsplit(z$text, '(?<=\\.)\\s+', perl = TRUE)
z$sentences <- sapply(lst1, function(x) paste(grep("test1", x, 
        value = TRUE), collapse=" "))

没有拆分的另一种选择是gsub

trimws(gsub("(([A-Za-z, ]*)test1[A-Za-z, ]+\\.?)(*SKIP)(*F)|.",
             "", z$text, perl = TRUE))
#[1] "test1 is good. Yet test1 is fake"   "test1 is bad. but test1 is better."
#[3] "" 

推荐阅读