以下是链接处理程序的代码:
link_patterns = {'http[s]?://www.facebook.[a-z]{2,3}/[A-Za-z0-9\.]*/videos/([0-9]+)*/':Facebook.get_video()}
def find_pattern(url):
for pattern in link_patterns:
if re.match(pattern, url):
return link_patterns[pattern]
return None
如何使用Facebook.get_video()
dict键的正则表达式获取带有id参数的link_patterns
?
答案 0 :(得分:1)
Python 3版本:
link_patterns = {'http[s]?://www.facebook.[a-z]{2,3}/[A-Za-z0-9\.]*/videos/(vb.[0-9]+/){0,1}([0-9]+)*/':Facebook.get_video}
def find_pattern(url):
for pattern, action in link_patterns.items():
matches = re.match(pattern, url)
if matches:
return matches.group(1), action
# or capture group that contains id in your case
return None
id, action = find_pattern(url)
if id:
action(id)
您可以返回一个函数对象,然后使用id作为参数调用它