【问题标题】:Matching multiple regular expressions in R [duplicate]在R中匹配多个正则表达式[重复]
【发布时间】:2016-01-01 07:37:57
【问题描述】:

我不确定这个问题之前是否已经解决过,至少是直接的。

我有这样一段:

“虽然我安抚他的所有努力都失败了,但我仍然希望他继续珍惜我们的友谊。过去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中的函数?

谢谢!

【问题讨论】:

    标签: regex r text


    【解决方案1】:

    看到这个postanswer - 归功于@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"
    

    【讨论】:

    • 非常感谢杰森!
    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多