Python URL中的Strip

2024-10-01 17:26:43 发布

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

我对python很陌生。我试图解析一个URL文件,只留下URL的一个特定部分(粗体部分)。在

以下是我使用的URL的一些示例:

http://www.mega.pk/**washingmachine**-dawlance/
http://www.mega.pk/**washingmachine**-haier/
http://www.mega.pk/**airconditioners**-acson/
http://www.mega.pk/**airconditioners**-lg/
http://www.mega.pk/**airconditioners**-samsung/

我尝试过一些正则表达式,但它变得非常复杂。我的想法是从所有url中删除这个“http://www.mega.pk/”,因为它很常见,然后删除“-”之后的所有内容,包括所有斜杠。但不知道怎么做。在


Tags: 文件httpurl示例wwwpkmegalg
3条回答

使用urlparse模块。它是专门为这个目的而建造的。在

from urlparse import urlparse

url = "http://www.mega.pk/washingmachine-dawlance/"

path = urlparse(url).path  # get the path from the URL ("/washingmachine-dawlnace/")
path = path[:path.index("-")]  # remove everything after the '-' including itself
path = path[1:]  # remove the '/' at the starting of the path (just before 'washing')

path变量的值为washingmachine

查看此(urlparse Python module of the week)以获取更多阅读内容。在

干杯!在

不使用正则表达式也可以实现相同的效果。Avinash提出的解决方案更简洁,但下面的方法可能更容易理解,尤其是如果您想在某个时候修改它:

s = '''http://www.mega.pk/washingmachine-dawlance/
http://www.mega.pk/washingmachine-haier/'''.splitlines()
for line in s:    
   cleanedUrl = line.replace('http://www.mega.pk/**','').replace('/','')
   urlParameters = cleanedUrl.split('-')
   print urlParameters[-1]

或者,如果您愿意,您可以使用更紧凑的版本:

^{pr2}$

使用re.sub

re.sub(r'^.*\/([^/]*)-.*', r'\1', line)

DEMO

示例:

^{pr2}$

相关问题 更多 >

    热门问题