我有一个像
这样的字符串数组urls_parts=['week', 'weeklytop', 'week/day']
我需要在我的网址中监控这些字符串的包含,所以这个例子只需要由每周顶部分触发:
url='www.mysite.com/weeklytop/2'
for part in urls_parts:
if part in url:
print part
但它当然也是由'周'引发的。 这样做的方法是什么?
OOps,让我指一下我的问题。 当url ='www.mysite.com / week / day / 2'和part ='week'时,我需要不触发该代码 需要触发的唯一网址是当part ='week'和url ='www.mysite.com / week / 2'或'www.mysite.com/week/2-second'时,例如
答案 0 :(得分:5)
我就是这样做的。
import re
urls_parts=['week', 'weeklytop', 'week/day']
urls_parts = sorted(urls_parts, key=lambda x: len(x), reverse=True)
rexes = [re.compile(r'{part}\b'.format(part=part)) for part in urls_parts]
urls = ['www.mysite.com/weeklytop/2', 'www.mysite.com/week/day/2', 'www.mysite.com/week/4']
for url in urls:
for i, rex in enumerate(rexes):
if rex.search(url):
print url
print urls_parts[i]
print
break
<强>输出强>
www.mysite.com/weeklytop/2
weeklytop
www.mysite.com/week/day/2
week/day
www.mysite.com/week/4
week
按长度排序的建议来自@Roman
答案 1 :(得分:3)
按照len
和break
从第一场比赛的循环中对您进行排序。
答案 2 :(得分:2)
尝试这样的事情:
>>> print(re.findall('\\weeklytop\\b', 'www.mysite.com/weeklytop/2'))
['weeklytop']
>>> print(re.findall('\\week\\b', 'www.mysite.com/weeklytop/2'))
[]
程序:
>>> urls_parts=['week', 'weeklytop', 'week/day']
>>> url='www.mysite.com/weeklytop/2'
>>> for parts in urls_parts:
if re.findall('\\'+parts +r'\b', url):
print (parts)
输出:
weeklytop
答案 3 :(得分:0)
为什么不这样使用urls_parts?
['/week/', '/weeklytop/', '/week/day/']
答案 4 :(得分:-1)
您的代码稍有变化就可以解决此问题 -
>>> for part in urls_parts:
if part in url.split('/'): #splitting the url string with '/' as delimiter
print part
weeklytop