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
What you're doing is pretty much defeating the efficiency of dict
s, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With