在Python中,如何将url字符串拆分成不同的部分?

2024-05-15 06:28:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我决定今晚学Python:) 我非常了解C(在其中编写了一个操作系统),所以我不是编程高手,所以python中的所有东西看起来都很简单,但我不知道如何解决这个问题: 假设我有这个地址:

http://example.com/random/folder/path.html 现在我如何从中创建两个字符串,其中一个包含服务器的“基本”名称,因此在本例中 http://example.com/ 另一个包含没有最后一个文件名的东西,所以在这个例子中 http://example.com/random/folder/ . 当然,我也知道找到第三个斜线和最后一个斜线的可能性,但也许你知道更好的方法:] 另外,在这两种情况下都使用斜杠是很酷的,但我不在乎,因为它可以很容易地添加。 所以有人有一个好的,快速的,有效的解决方案吗?还是只有“我的”解决方案,找到斜线?

谢谢!


Tags: path字符串服务器名称comhttpexample地址
3条回答

如果这是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.r部分:

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)

python 2.x中的urlparse模块(或者python 3.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操作有一个特殊的引用,所以一切都很好。

我没有使用Python的经验,但是我找到了urlparse module,它应该可以完成这项工作。

相关问题 更多 >

    热门问题