代码之家  ›  专栏  ›  技术社区  ›  Jeremy K.

我怎样才能只替换某些位置的文本,例如(“披头士”或“披头士,THE”)

  •  1
  • Jeremy K.  · 技术社区  · 7 年前

    我有一些这样格式的数据:

                       Name Number
    1           The Beatles    100
    2   Rolling Stones, The    100
    3 Puff The Magic Dragon    100
    4         The Offspring    100
    
    df <- data.frame(stringsAsFactors=FALSE,
            Name = c("The Beatles", "Rolling Stones, The", "Puff The Magic Dragon",
                     "The Offspring"),
          Number = c(100L, 100L, 100L, 100L)
    )
    

    • 当它开始的时候。所以“披头士”应该是“披头士”

    但我想离开:

    • “吹神龙”应该是一个人。

    这是我尝试过的,但是它从“神龙泡芙”中去掉了“the”,这不是我想要的。

    library(stringr)
    df$Name <- str_replace(string = df$Name, "\\, The", "")
    df$Name <- str_replace(string = df$Name, "The", "")
    

    给出:

                    Name Number
    1            Beatles    100
    2     Rolling Stones    100
    3 Puff  Magic Dragon    100
    4          Offspring    100
    

    而我期望的结果是:

                    Name Number
    1            Beatles    100
    2     Rolling Stones    100
    3 Puff The Magic Dragon 100
    4          Offspring    100
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Calum You    7 年前

    你可以用锚 ^ $ 指示每个字符串的开头和结尾。也可以将阵列组与 | 只使用一种模式,并且可以使用便利功能 str_remove() str_replace(replacement = "") . 这些是 正则表达式 here

    library(tidyverse)
    df <- data.frame(
      stringsAsFactors = FALSE,
      Name = c(
        "The Beatles", "Rolling Stones, The", "Puff The Magic Dragon",
        "The Offspring"
      ),
      Number = c(100L, 100L, 100L, 100L)
    )
    df %>%
      mutate(Name = str_remove_all(Name, "(^The )|(, The$)"))
    #>                    Name Number
    #> 1               Beatles    100
    #> 2        Rolling Stones    100
    #> 3 Puff The Magic Dragon    100
    #> 4             Offspring    100
    

    于2019-03-14由 reprex package

        2
  •  2
  •   Ronak Shah    7 年前

    sub

    sub("^The |, The$", "", df$Name)
    
    #[1] "Beatles"   "Rolling Stones"  "Puff The Magic Dragon" "Offspring"  
    

    或与 str_replace

    library(tidyverse)
    
    df %>%
      mutate(Name = str_replace(Name, "^The |, The$", ""))
    
    #                   Name Number
    #1               Beatles    100
    #2        Rolling Stones    100
    #3 Puff The Magic Dragon    100
    #4             Offspring    100