This article describes how to use a regular expression to select callback in Python. it involves the use of Python regular expressions and callback functions. it has some reference value, for more information about how to use a regular expression to select callback, see the example in this article. Share it with you for your reference. The details are as follows:
Recently, I was wondering how to use xpath to precisely capture the body of the article. Similar ideas with parselets are simpler.
In code design, the regular expression is used to match the URL and then the callback handler method is used. for details, refer to the Dispatcher of web. py ).
Of course, this implementation is quite simple, and all functions are called back, without classes.
#!/bin/env pythonimport re, sys# Define parser first.def baidu(username): # Business logic return "Using parser Baidu. and the user's name is: %s." % usernamedef qzone(uin): # Business logic return "Using parser Qzone, and the user's QQ is: %s." % uin# From web.pydef group(seq, size):#{{{ """ Returns an iterator over a series of lists of length size from iterable. >>> list(group([1,2,3,4], 2)) [[1, 2], [3, 4]] >>> list(group([1,2,3,4,5], 2)) [[1, 2], [3, 4], [5]] """ def take(seq, n): for i in xrange(n): yield seq.next() if not hasattr(seq, 'next'): seq = iter(seq) while True: x = list(take(seq, size)) if x: yield x else: break#}}}def parser_init(url,mapping): for pat, what in group(mapping,2): result = re.compile('^' + pat + '$').match(url) if result: return what, [x for x in result.groups()] return None, Noneif __name__ == '__main__': mapping = ( 'http://(?:hi|space).baidu.com/([^/]+)(?:/.*)?','baidu', 'http://(\d+).qzone.qq.com(?:/.*)?','qzone', ) (func, args) = parser_init(sys.argv[1],mapping) if func: callback = func if func in globals(): callback = globals()[func] if callable(callback): print callback(*args) else: print 'No parser found.';
I hope this article will help you with Python programming.