在python中,使用最快的方式将scheme://netloc/path;parameters?query#fragment
类型的网址转换为"方案相对"或"协议相对" URI?
目前,我正在使用this的版本,但我认为可能有更简洁/更快的方式来完成此任务。输入始终附加https://
或http://
。
答案 0 :(得分:1)
我能找到的最快的方法是str.partition
:
In [1]: url = 'https://netloc/path;parameters?query#fragment'
In [2]: %timeit url.partition('://')[2]
The slowest run took 6.70 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 251 ns per loop
In [3]: %timeit url.split('://', 1)[1]
The slowest run took 5.20 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 407 ns per loop
In [4]: %timeit url.replace('http', '', 1).replace('s://', '', 1)
The slowest run took 4.24 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 589 ns per loop
由于您所做的只是剥离以固定字符串结尾的文本,因此解析URL似乎没什么好处。
答案 1 :(得分:0)
from urlparse import urlparse
o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
print o.scheme
print o.netloc
print o.path
我可能会这样做......