Match regular expressions on dictionary keys

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

Now we need to find the word in the dictionary. Key K must match "Hello World" or "Testing" exactly to use.

So let ours text = 'hello world'still want this to returnvalue1

So, how do we deal with this regular expression of matching text with keys? Ideally, we don't want to iterate through a dictionary

Edit: An aspect of an aspect is just a simple example. The text may change if it is a combination of numbers and letters that we want to match. We will usually use a regex pattern

+4
source share
4

, , dict s, , , dict. :

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

:

>>> 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
>>> 

dict. . .

"no iteration", , , .

+2

,

>>> d = {'Hello World': 'value1', 'Testing': 'value2'}
>>> text = 'hello     world'
>>> key = next(x for x in (re.search(r'(?i)' + re.sub(r'(\s)+', r'\1', text.strip()), i) for i in d.keys()) if x).group()
>>> d[key]
'value1'
0

, , , , , - , .

from bisect import bisect_left

d = {'Hello World': "value1", 'Testing': "value2"}

items = sorted([(k.lstrip().lower(),v) for k, v in d.items()])

text = 'hello     world'
ind = bisect_left(items,(text.lower(),), hi=len(items) - 1)
# use items[ind]

, :

from collections import defaultdict
lookup_mapping = defaultdict(list)

for k in d:
    lookup_mapping[k[:2].lower().lstrip()].append(k)

poss =  lookup_mapping[text[:2].lower().lstrip()]

, , .., , , , , , , , .

0
source

Perhaps consider normalizing keys in your dict. Using python's string.split function without a separator will remove all spaces.

def normalize(word):
    return " ".join(word.split()).lower()
d = {'Hello World': 'value1', 'Testing': 'value2'}
d = {normalize(k): v for k, v in d.items()} 
print(d)
>>> {'hello world': 'value1', 'testing': 'value2'}
text = 'hello     world'
d[normalize(text)]
>>> 'value1'
0
source

Source: https://habr.com/ru/post/1629567/


All Articles