python - python中的正则表达式字典

标签 python regex performance mapping

是否可以实现一个以键为正则表达式、 Action (带参数)为值的字典?

例如

  1. key = "actionname 1 2", value = "method(1, 2)"
  2. key = "differentaction par1 par2", value = "appropriate_method(par1, par2)"

用户在键中键入,我需要使用作为用户输入的一部分提供的参数执行匹配方法。

如果我们能在 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)

关于python - python中的正则表达式字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10931044/

相关文章:

Python,Pandas删除指定列中具有特定值的行

python - 在 Maya 中设置对象的大小 - 比例值与精确单位

regex - 从文本文件中的重复范围模式中获取特定行

php - 如何在 PHP 中对磁盘 IO 进行基准测试?与MySQL?

performance - 一个java进程可以使用多少个cpu核心?

python - 尝试计算 softmax 值,得到 AttributeError : 'list' object has no attribute 'T'

python - numpy 数组大小的困惑

regex - 如何从两个文件中读取内容并合并到 bash shell 中的第三个文件

javascript - 使用正则表达式将电子邮件与公司 URL 进行匹配

performance - 语音识别,例如 Siri