首页 > 解决方案 > 提取特定单词前后的 5 个单词

问题描述

如何提取特定单词旁边的单词/句子?例子:

“6月28日,简去电影院吃了爆米花”

我想选择'Jane'并得到[-2,2],意思是:

“6月28日,简去”

标签: r

解决方案


这是一个扩展多次出现的示例。基本上,在空白处拆分,找到单词,扩展索引,然后列出结果。

s <- "On June 28, Jane went to the cinema and ate popcorn. The next day, Jane hiked on a trail."
words <- strsplit(s, '\\s+')[[1]]
inds <- grep('Jane', words)
lapply(inds, FUN = function(i) {
  paste(words[max(1, i-2):min(length(words), i+2)], collapse = ' ')
})
#> [[1]]
#> [1] "June 28, Jane went to"
#> 
#> [[2]]
#> [1] "next day, Jane hiked on"

reprex 包(v0.3.0)于 2019 年 9 月 17 日创建


推荐阅读