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

R语言字符串处理:按规则移除间隔出现的指定水果词汇

问题描述

我有如下字符串列表:

string <- c("tasty apple", "tasty orange", "yellow banana", "red tasty peach", "tasty banana apple", "tasty apple yellow banana", "yellow orange banana", "peach tasty apple", "yellow banana tasty peach")

当字符串仅含一种水果时无需处理;若包含两种及以上水果,需遵循以下匹配模式与替换规则:

pattern <- c("banana apple", "banana orange", "peach apple", "banana peach")
replacement <- c("apple", "banana", "peach", "banana")

目前仅能处理水果词汇相邻的情况,当水果词之间夹杂其他单词、或顺序与规则不同时,无法正确按规则移除对应水果词,期望处理后达到如下效果:

处理前处理后
tasty appletasty apple
tasty orangetasty orange
yellow bananayellow banana
red tasty peachred tasty peach
tasty banana appletasty apple
tasty apple yellow bananatasty apple yellow
yellow orange bananayellow banana
peach tasty applepeach tasty
yellow banana tasty peachyellow banana tasty

解决方案

思路说明

先提取字符串中的水果集合,对照规则判断需保留和移除的水果,再从原字符串中剔除指定水果词,无需依赖水果词的相邻性或顺序。

实现代码

首先定义水果列表,将规则转换为结构化的键值对:

# 定义所有涉及的水果
fruits <- c("apple", "orange", "banana", "peach")

# 将规则转换为数据框,方便匹配水果组合
rule_df <- data.frame(
  fruit1 = sapply(strsplit(pattern, " "), `[`, 1),
  fruit2 = sapply(strsplit(pattern, " "), `[`, 2),
  keep = replacement,
  stringsAsFactors = FALSE
)

编写处理单个字符串的函数:

process_string <- function(s) {
  # 拆分字符串为单词列表
  words <- strsplit(s, " ")[[1]]
  # 提取当前字符串中的所有水果
  found_fruits <- intersect(words, fruits)
  
  # 仅含一种或无水果,直接返回原字符串
  if (length(found_fruits) <= 1) {
    return(s)
  }
  
  # 遍历规则,匹配水果组合
  for (i in seq(nrow(rule_df))) {
    if (all(c(rule_df$fruit1[i], rule_df$fruit2[i]) %in% found_fruits)) {
      # 确定要移除的水果(保留规则指定的水果)
      remove_fruit <- setdiff(found_fruits, rule_df$keep[i])
      # 移除目标水果词,保留其他单词
      new_words <- words[words != remove_fruit]
      # 拼接为新字符串并返回
      return(paste(new_words, collapse = " "))
    }
  }
  
  # 无匹配规则时返回原字符串
  return(s)
}

应用函数处理所有字符串:

# 批量处理字符串
result <- sapply(string, process_string)

# 输出结果
print(result)

运行结果

tasty apple        tasty orange       yellow banana 
      "tasty apple"       "tasty orange"      "yellow banana" 
    red tasty peach    tasty banana apple tasty apple yellow banana 
   "red tasty peach"       "tasty apple"    "tasty apple yellow" 
 yellow orange banana     peach tasty apple yellow banana tasty peach 
     "yellow banana"        "peach tasty"    "yellow banana tasty" 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:22:45