File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ from .fuzzymap import FuzzyMap
2
+
3
+ __all__ = ('FuzzyMap' ,)
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments