【问题标题】:How to Convert "space" into "%20" with R如何使用 R 将“空格”转换为“%20”
【发布时间】:2012-06-20 09:21:50
【问题描述】:

参考标题,我正在考虑如何将单词之间的空格转换为 %20 。

例如,

> y <- "I Love You"

如何制作y = I%20Love%20You

> y
[1] "I%20Love%20You"

非常感谢。

【问题讨论】:

    标签: r curl rcurl


    【解决方案1】:

    另一个选项是URLencode():

    y <- "I love you"
    URLencode(y)
    [1] "I%20love%20you"
    

    【讨论】:

    • +1 比我的答案更好,并且很好地提醒了此功能的存在
    • 需要注意的是这里只是把""换成了%20,如果需要转换别人,RCurl::curlEscape()更好。
    • @AmitKohli 如果您需要转换其他字符(例如!$&amp;'()*+,;=:/?@#[] ),您也可以使用URLencode,参数reserved 设置为TRUE
    【解决方案2】:

    gsub() 是一种选择:

    R> gsub(pattern = " ", replacement = "%20", x = y)
    [1] "I%20Love%20You"
    

    【讨论】:

      【解决方案3】:

      RCurl 包中的函数 curlEscape() 完成了这项工作。

      library('RCurl')
      y <- "I love you"
      curlEscape(urls=y)
      [1] "I%20love%20you"
      

      【讨论】:

      • 请注意,这会将 "test!:" 更改为 "test%21%3A%20" vs URLencode "test!%3a%20"
      【解决方案4】:

      我喜欢URLencode(),但请注意,如果您的 url 已经包含 %20 和真实空格,有时它不会按预期工作,在这种情况下,甚至 URLencode()repeated 选项都不会你想要什么。

      就我而言,我需要同时运行 URLencode()gsub 才能得到我需要的东西,如下所示:

      a = "already%20encoded%space/a real space.csv"
      
      URLencode(a)
      #returns: "encoded%20space/real space.csv"
      #note the spaces that are not transformed
      
      URLencode(a, repeated=TRUE)
      #returns: "encoded%2520space/real%20space.csv"
      #note the %2520 in the first part
      
      gsub(" ", "%20", URLencode(a))
      #returns: "encoded%20space/real%20space.csv"
      

      在这个特定的示例中,单独使用 gsub() 就足够了,但 URLencode() 当然不仅仅是替换空格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 2011-07-31
        • 1970-01-01
        • 2012-03-03
        • 2011-04-11
        相关资源
        最近更新 更多