如何使用R将“空格”转换为“%20”

问题描述 投票:3回答:4

参考标题,我想知道如何将单词之间的空格转换为%20。

例如,

> y <- "I Love You"

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

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

非常感谢。

r curl rcurl
4个回答
8
投票

gsub()是一种选择:

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

19
投票

另一个选项是URLencode()

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

1
投票

来自软件包curlEscape()的功能RCurl完成工作。

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

1
投票

[我喜欢URLencode(),但要注意,如果您的网址中已经包含%20和一个实际空间,有时它就无法按预期工作,在这种情况下,甚至repeatedURLencode()选项都无法执行您想要的。

就我而言,我需要连续运行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()当然要做的不仅仅是替换空格。

© www.soinside.com 2019 - 2024. All rights reserved.