gpt4 book ai didi

python - 使用 python 正则表达式匹配 url 中的类别?

转载 作者:太空宇宙 更新时间:2023-11-04 08:50:34 25 4
gpt4 key购买 nike

我想匹配以下 url 中的类别:newspolitics

请注意,可能有 1 个或多个类别。可以通过在文本或数字的一侧添加一个 / 并在其间添加一个 / 来识别类别。

我尝试过的:

item.url = 'http://www.example.com/news/politics/this-is-article-name-1993591'

compiled_regex = re.compile('/.+(?!/)/')

match = compiled_regex.search(item.url)

响应是

我想要什么(预期结果):

match.group(0) = `news`
match.group(1) = `politics`

最佳答案

我不会使用正则表达式,而是使用 urllib.parse这是用来解析 url 等的

>>> url = 'http://www.example.com/news/politics/this-is-article-name-1993591'
>>> import urllib.parse

>>> urllib.parse.urlparse(url)
ParseResult(scheme='http',
netloc='www.example.com',
path='/news/politics/this-is-article-name-1993591',
params='',
query='',
fragment='')

>>> urllib.parse.urlparse(url).path
'/news/politics/this-is-article-name-1993591'

>>> urllib.parse.urlparse(url).path.split('/')[1:-1]
['news', 'politics']

关于python - 使用 python 正则表达式匹配 url 中的类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35797675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com