我决定今晚学习python :)我非常了解C语言(在里面写了一个操作系统),所以我不是编程新手,所以python中的一切看起来都很容易,但我不知道如何解决这个问题:假设我有这个地址:
现在我该如何创建两个字符串,一个包含服务器的“基本”名称,因此在本例中是http://example.com/,另一个包含没有最后一个文件名的内容,所以在本例中是http://example.com/random/folder/。此外,我当然知道分别找到第三个和最后一个斜杠的可能性,但也许你知道更好的方法:]而且在两种情况下都有尾部斜杠是很酷的,但我不在乎,因为它可以很容易地添加。所以有没有人有一个好的,快速的,有效的解决方案?还是只有“我”的解决方案,找到斜杠?
谢谢!
发布于 2009-01-16 08:14:37
Python2.x中的urlparse模块(或者python3.x中的urllib.parse )就是这样做的。
>>> from urllib.parse import urlparse
>>> url = 'http://example.com/random/folder/path.html'
>>> parse_object = urlparse(url)
>>> parse_object.netloc
'example.com'
>>> parse_object.path
'/random/folder/path.html'
>>> parse_object.scheme
'http'
>>>
如果你想在url下的文件路径上做更多的工作,你可以使用posixpath模块:
>>> from posixpath import basename, dirname
>>> basename(parse_object.path)
'path.html'
>>> dirname(parse_object.path)
'/random/folder'
在此之后,您可以使用posixpath.join将各个部分粘合在一起。
编辑:我完全忘记了windows用户会被os.path中的路径分隔符卡住。我阅读了posixpath模块文档,它有一个关于URL操作的特殊引用,所以一切都很好。
发布于 2009-01-16 08:11:11
如果这就是URL解析的范围,那么Python内置的rpartition就可以完成这项工作:
>>> URL = "http://example.com/random/folder/path.html"
>>> Segments = URL.rpartition('/')
>>> Segments[0]
'http://example.com/random/folder'
>>> Segments[2]
'path.html'
在Pydoc上,str.rpartition:
Splits the string at the last occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself
这意味着rpartition将为您执行搜索,并在您指定的字符(在本例中为/ )的最后一个(最右侧)处拆分字符串。它返回一个包含以下内容的元组:
(everything to the left of char , the character itself , everything to the right of char)
发布于 2009-01-16 07:49:55
我没有使用Python的经验,但我找到了urlparse module,它应该可以完成这项工作。
https://stackoverflow.com/questions/449775
复制相似问题