Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex matching on dictionary keys

Imagine we have a dictionary: {'Hello World': value1, 'Testing': value2}

Now we need to look up a word in the dictionary. The key K will need to exactly match 'Hello World' or 'Testing', to use.

So let our text = 'hello world' we still want this to return value1

So how do we handle this regex matching of text to keys? Ideally we don't want to iterate through the dictionary

Edit: Spacing aspect is just a simple example. The text may change in case, be a combination of numbers and letters we want to match. We would usually use a regex pattern

like image 267
redrubia Avatar asked Sep 26 '22 08:09

redrubia


1 Answers

What you're doing is pretty much defeating the efficiency of dicts, so you're probably better off making your own dict-like class. Here's a simple example:

from re import search, I

class RegexMap(object):
    def __init__(self, *args, **kwargs):
        self._items = dict(*args, **kwargs)
    def __getitem__(self, key):
        for regex in self._items.keys():
            if search(regex, key, I):
                return self._items[regex]
        raise KeyError

Usage:

>>> rm = RegexMap({'\s*hello\s*world\s*':1, '\s*foo\s*bar\s*':2})
>>> rm['Hello World']
1
>>> rm['foobar']
2
>>> rm['baz']
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    rm['baz']
  File "C:\Users\dmurphy\Documents\python\_t.py", line 10, in __getitem__
    raise KeyError
KeyError
>>> 

From there, you can add more dict functionality. See the Data Model docs.

It does break your "no iteration" clause, but I'm not sure there's any way around that if you want to generalize to regexes.

like image 128
glibdud Avatar answered Sep 28 '22 04:09

glibdud