python中的正则表达式字典
发布时间:2020-12-20 12:28:26 所属栏目:Python 来源:网络整理
导读:是否可以使用键作为正则表达式和操作(带参数)作为值来实现字典? 例如 key =“actionname 1 2”,value =“method(1,2)” key =“differentaction par1 par2”,value =“proper_method(par1,par2)” 密钥中的用户类型,我需要使用作为用户输入的一部分提供的参
是否可以使用键作为正则表达式和操作(带参数)作为值来实现字典?
例如 > key =“actionname 1 2”,value =“method(1,2)” 密钥中的用户类型,我需要使用作为用户输入的一部分提供的参数来执行匹配方法. 如果我们能够在O(1)时间内完成查找,那将是很好的,即使它至少不可能,我正在寻找解决方案来解决这个问题. 我将有几百个正则表达式(比如300)和匹配的参数化动作来执行. 我可以写一个循环来实现这一点,但有没有优雅的方法来做到这一点,而不使用for循环? 相关问题:Hashtable/dictionary/map lookup with regular expressions 解决方法
是的,这是完全可能的:
import re dict = {} dict[re.compile('actionname (d+) (d+)')] = method dict[re.compile('differentaction (w+) (w+)')] = appropriate_method def execute_method_for(str): #Match each regex on the string matches = ( (regex.match(str),f) for regex,f in dict.iteritems() ) #Filter out empty matches,and extract groups matches = ( (match.groups(),f) for match,f in matches if match is not None ) #Apply all the functions for args,f in matches: f(*args) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |