【问题标题】:How to use map with str_replace_all for multiple pattern replacements如何使用带有 str_replace_all 的 map 进行多个模式替换
【发布时间】:2021-10-25 15:33:48
【问题描述】:

我有一个字符串,想将两个小写单词大写。以下完成了我想要的:

library(tidyverse)

"this is a test" %>% 
  str_replace_all("this", toupper("this")) %>% 
  str_replace_all("test", toupper("test"))

但是,我想以更有效的方式执行此操作,因为我有很多模式要替换,并且不希望每个模式有单独的行。我考虑过使用map,但是我无法让它正确执行,因为下面的代码会引发错误:

"this is a test" %>% 
  c("this", "test") %>% 
  map_chr(~str_replace_all(.x, toupper(.x)))

谁能告诉我如何做到这一点?

【问题讨论】:

    标签: r regex string


    【解决方案1】:

    另一种使用Reduce + gsub的递归方法

    > Reduce(
    +   function(x, p) gsub(paste0("(", p, ")"), "\\U\\1", x, perl = TRUE),
    +   val,
    +   string
    + )
    [1] "THIS is a TEST"
    

    【讨论】:

      【解决方案2】:

      tidyverse 中,我们可以使用reduce 来执行此操作

      library(stringr)
      library(purrr)
      reduce(val, ~ str_replace_all(.x, .y, toupper(.y)), .init = string)
      [1] "THIS is a TEST"
      

      数据

      val <- c("this", "test")
      string <- "this is a test"
      

      【讨论】:

        【解决方案3】:

        这是一个打包成函数的替代方法。

        > SomeToUpper <- function(string_all, word_vector){
        +   return(paste(
        +     sapply(
        +       unlist(str_split(string_all, " ")),
        +       function(word){ 
        +         ifelse(
        +           word %in% word_vector, 
        +           str_to_upper(word), 
        +           word)}),
        +     collapse = " ")
        +   )
        + }
        > SomeToUpper("this is a test", c("this", "test"))
        [1] "THIS is a TEST"
        

        【讨论】:

          【解决方案4】:

          在正则表达式中,您可以使用\\U 将捕获组更改为大写。使用| 分隔不同的模式。

          val <- c("this", "test")
          string <- "this is a test"
          
          gsub(sprintf('(%s)', paste0(val, collapse = '|')), '\\U\\1', string, perl = TRUE)
          #[1] "THIS is a TEST"
          

          要回答您的问题,您可以使用for 循环来实现您正在寻找的结果。

          for(i in val) {
            string <- stringr::str_replace_all(string, i, toupper(i))   
          }
          

          map/lapply 没有关于中间发生的变化的“知识”,因此它适用于相同的输入。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-09-30
            • 1970-01-01
            • 2021-11-12
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多