Skip to content

Commit e85f552

Browse files
Merge pull request #1 from ArtyomVancyan/master
Implement FuzzyMap major behavior
2 parents 59bbc30 + a7f6d1f commit e85f552

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from .fuzzymap import FuzzyMap
2+
3+
__all__ = ('FuzzyMap',)

fuzzymap.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from fuzzywuzzy import fuzz
2+
3+
4+
class FuzzyMap(dict):
5+
"""
6+
FuzzyMap implements a subtype of `dict` with customized descriptors.
7+
8+
This kind of dictionary returns the value of the exact key if there is
9+
such a key. Otherwise, it will return the value of the most similar key
10+
satisfying the given ratio. The same mechanism works when setting a new
11+
or replacing an old key in the dictionary. If the key is not found and
12+
does not match any of the keys by the given ratio, it returns `None`.
13+
"""
14+
15+
ratio = 60
16+
17+
def closest_key(self, key):
18+
"""Returns the closest key matched by the given ratio"""
19+
20+
if len(self):
21+
# Calculate the ratio of each key using fuzzywuzzy
22+
coefficients = {k: fuzz.ratio(k, key) for k in self.keys()}
23+
matching = max(coefficients, key=lambda k: coefficients[k])
24+
if coefficients[matching] > self.ratio:
25+
return matching
26+
return key
27+
28+
def __missing__(self, key):
29+
return super().get(self.closest_key(key))
30+
31+
def __setitem__(self, key, value):
32+
super().__setitem__(self.closest_key(key), value)

0 commit comments

Comments
 (0)