r - 提取特定单词前后的 5 个单词
问题描述
如何提取特定单词旁边的单词/句子?例子:
“6月28日,简去电影院吃了爆米花”
我想选择'Jane'并得到[-2,2],意思是:
“6月28日,简去”
解决方案
这是一个扩展多次出现的示例。基本上,在空白处拆分,找到单词,扩展索引,然后列出结果。
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 日创建
推荐阅读
- java - 如何支持连接池供应商特定的 DataSourceProperties 配置
- c# - C# 中的 FluentValidation - 使用另一个对象中的属性进行验证
- xcode - Flutter iOS 构建失败 - 快照(IOSArch.armv7)以非零退出代码退出:-4
- php - 登录页面空白
- botframework - ConversationState 和 UserState 有什么区别?
- javascript - 单击提交按钮时如何传递单击按钮的值?
- r - 从R中的另一个表信息创建一个表
- r - 数据框中散布的分类值的累积计数,独立于每个 id
- php - 无法安装composer PHP版本错误
- jmeter - 解析异常 - jMeter json 后处理器;在提取json响应的最后一个元素时