如果一个词与其他词一起出现在字符串中,则将其删除

问题描述 投票:0回答:1

我有一个这样的字符串列表:

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")

当字符串中只有一种水果时就可以了。但是,当它们超过 2 个时,我有一个模式和替换列表:

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

当它们在字符串中彼此相邻时,我可以删除其中一个水果,但是在我的数据中,它们之间可能有单词,我不知道如何删除单词。字符串中单词的顺序也可能不同。

我希望它是这样的:

之前 之后
好吃的苹果 好吃的苹果
美味的橙子 美味的橙子
黄香蕉 黄香蕉
红桃 红桃
美味的香蕉苹果 好吃的苹果
美味的苹果黄香蕉 美味的苹果黄
黄橙香蕉 黄香蕉
桃子好吃的苹果 桃子好吃
黄香蕉香桃 黄香蕉好吃
r stringr
1个回答
0
投票

这是一个使用嵌套 for 循环的简单解决方案。这个想法是 (1) 反转替换字符串,因此它显示要删除的单词,并且 (2) 然后检测模式是字符串的一部分的情况,以及 (3) 删除单词,在 (1) 中定义:

    reverse_replacement <- unlist(lapply(1:length(pattern), 
                                  function(x) {
                                    stringr::str_trim(stringr::str_remove(pattern[x], replacement[x]), "both") }))
index = 0
for (word_combi in string) {
  index <- index  + 1
  index_pattern <- 0
  
  for (pat in pattern) {
    index_pattern <- index_pattern + 1
    words_pattern <- stringr::str_split(pat, " ", n = Inf, simplify = FALSE)[[1]]
    words <- stringr::str_detect(word_combi, words_pattern)
    
    if (sum(words) == length(words_pattern)) {
      string[index] <- stringr::str_trim(stringr::str_remove(word_combi, reverse_replacement[index_pattern]), "both")
    }
  }
}

string
[1] "tasty apple"         "tasty orange"        "yellow banana"       "red tasty peach"    
[5] "tasty  apple"        "tasty apple yellow"  "yellow  banana"      "peach tasty"        
[9] "yellow banana tasty"
© www.soinside.com 2019 - 2024. All rights reserved.