Python Reg模式URL选择/筛选
目标:获取包含(/yyyy/mm/dd/ddd/)格式的链接。e、 g./2017/03/10/519650091/ 由于某些原因,它总是有facebook、twitter和2017/03/20170311格式的链接Python Reg模式URL选择/筛选,python,regex,Python,Regex,目标:获取包含(/yyyy/mm/dd/ddd/)格式的链接。e、 g./2017/03/10/519650091/ 由于某些原因,它总是有facebook、twitter和2017/03/20170311格式的链接 links = [ 'http://www.npr.org/sections/thesalt/2017/03/10/519650091/falling-stars-negative-yelp-reviews-target-trump-restaurants-hotels',
links = [
'http://www.npr.org/sections/thesalt/2017/03/10/519650091/falling-stars-negative-yelp-reviews-target-trump-restaurants-hotels',
'https://ondemand.npr.org/anon.npr-mp3/npr/wesat/2017/03/20170311_wesat_south_korea_wrap.mp3?orgId=1&topicId=1125&d=195&p=7&story=519807707&t=progseg&e=519805215&seg=12&siteplayer=true&dl=1',
'https://www.facebook.com/NPR',
'https://www.twitter.com/NPR']
这里有几个问题:
^(/[0-9]{4}/[0-9]{2}/[0-9]{2}/[0-9]{9})$
要求字符串以/[0-9]{4}/
开头,但所有字符串都以http
开头r.search(链接)=“None”
永远不会为真,因为re.search
返回None
或匹配对象,因此与字符串“None”
进行比较是不合适的sel_links = []
def selectedLinks(links):
r = re.compile("^(/[0-9]{4}/[0-9]{2}/[0-9]{2}/[0-9]{9})$")
for link in links:
if r.search(link)!="None":
sel_links.append(link)
return set(sel_links)
selectedLinks(links)
下次请正确设置问题的格式,并确保发布的代码中没有输入错误(我在
链接中更正了=
)
def selectedLinks(links):
r = re.compile(r"/[0-9]{4}/[0-9]{2}/[0-9]{2}/[0-9]{9}")
for link in links:
if r.search(link):
sel_links.append(link)
return set(sel_links)