您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

选择要基于正则表达式调用的Python函数

选择要基于正则表达式调用的Python函数

我认为创建匿名函数的困难有点让人头疼。您真正想要做的是将相关代码保持在一起,并使代码整齐。因此,我认为装饰师可能会为您工作。

import re

# List of pairs (regexp, handler)
handlers = []

def handler_for(regexp):
    """Declare a function as handler for a regular expression."""
    def gethandler(f):
        handlers.append((re.compile(regexp), f))
        return f
    return gethandler

@handler_for(r'^<\w+> (.*)')
def handle_message(msg):
    print msg

@handler_for(r'^\*{3} (.*)')
def handle_warning(msg):
    global num_warnings, num_fatals
    num_warnings += 1
    if is_fatal(msg):
        num_fatals += 1
python 2022/1/1 18:47:12 有339人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶