在R中匹配多个正则表达式

3

我不确定这个问题是否以直接形式被解决过。

我有一个段落像这样:

“虽然我所有平息他的努力都失败了,但我仍然希望他能继续珍视我们的友谊。我们已经是过去18年的好朋友了,我不知道为什么一点意见上的分歧就会让他如此生气!唉,人生很奇妙,它有它的方式吧。”

我想在段落中进行以下替换:

 "While all my efforts" -> <my-attempt>
 "to pacify him" -> <to-make-things-better>
 "failed" -> <failure>
 "I still hoped" -> <hope>
 "we had been great friends" -> <we-were-friends>
 "so mad" -> <unhappy>

其它文本保持不变。

能否使用R中的正则表达式函数一次性完成这个操作?

谢谢!

1个回答

3

请参考此帖子答案 - 感谢@TheodoreLytras:

text <- c("While all my efforts to pacify him failed, I still hoped that he would continue to value our friendship. We had been great friends for the past 18 years, and I don't know why a simple difference of opinion should make him so mad! Well, life is strange, and has its ways, I guess")

mgsub <- function(pattern, replacement, x, ...) {
  if (length(pattern)!=length(replacement)) {
    stop("pattern and replacement do not have the same length.")
  }
  result <- x
  for (i in 1:length(pattern)) {
    result <- gsub(pattern[i], replacement[i], result, ...)
  }
  result
}

patterns <- c("While all my efforts",
              "to pacify him",
              "failed",
              "I still hoped",
              "we had been great friends",
              "so mad")

replacements <- c("<my-attempt>",
                  "<to-make-things-better>",
                  "<failure>",
                  "<hope>",
                  "<we-were-friends>",
                  "<unhappy>")

mgsub(pattern = patterns, replacement = replacements, x = text)
# [1] "<my-attempt> <to-make-things-better> <failure>, <hope> that he would continue to value our friendship. We had been great friends for the past 18 years, and I don't know why a simple difference of opinion should make him <unhappy>! Well, life is strange, and has its ways, I guess"

非常感谢你,Jason! - Venkat Ramakrishnan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接