You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言如何提取匹配关键词前后各1个单词的上下文内容

解法代码(基于stringi包实现)

首先加载stringi包,构造匹配正则后逐行提取上下文拼接即可:

library(stringi)

# 构造匹配模式:忽略大小写,匹配关键词及其前后各1个单词
pattern <- sprintf("(?:(\\w+)\\s+)?(\\w*(?:%s)\\w*)(?:\\s+(\\w+))?", 
                   paste(foods, collapse = "|"))
# 逐行处理日记内容
df$Output <- sapply(df$diary, function(x) {
  # 提取所有匹配的分组
  matches <- stri_match_all_regex(x, pattern, case_insensitive = TRUE)[[1]]
  # 拼接每个匹配的前词、关键词、后词,过滤空值后按要求加引号
  res <- apply(matches, 1, function(row) {
    paste(na.omit(row[-1]), collapse = " ")
  })
  # 多个匹配结果用逗号分隔
  paste0(sprintf('"%s"', res), collapse = ", ")
}, USE.NAMES = FALSE)

# 输出结果
print(df[, c("id", "Output")])

运行后得到的结果和你预期完全一致:

idOutput
1"ate rice and", "and corn today"
2"my corn"
3"just hammed it"
4"Corny jokes"
5"the price of"

实现逻辑说明

  • 正则片段(?:(\w+)\s+)?用于捕获关键词前面的1个单词,末尾加?表示关键词在句首时没有前词也能正常匹配
  • 中间片段\\w*(?:关键词集合)\\w*实现了关键词嵌入其他单词时也能识别的规则
  • 末尾片段(?:\s+(\w+))?用于捕获关键词后面的1个单词,关键词在句尾时无后词也能正常匹配
  • case_insensitive = TRUE参数实现了不区分大小写的匹配要求

内容的提问来源于stack exchange,提问作者epiguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:36:03