Last active
December 14, 2015 03:09
-
-
Save karanlyons/5018869 to your computer and use it in GitHub Desktop.
For when a dictionary is too boring.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2.7 | |
# -*- coding: utf-8 -*- | |
from decimal import Decimal | |
from difflib import get_close_matches | |
class Thesaurus(dict): | |
''' | |
For when a dictionary is too boring. | |
''' | |
def __getitem__(self, key): | |
keys = dict.keys(self) | |
try: | |
keys.remove(key) | |
except ValueError: | |
pass | |
try: | |
return dict.__getitem__(self, self.__get_synonyms(key, keys, 1, 0.6)[0]) | |
except IndexError, TypeError: | |
return dict.__getitem__(self, key) | |
@staticmethod | |
def __get_synonyms(needle, haystack, n, cutoff): | |
if type(needle) in (str, unicode): | |
haystack = [hay for hay in haystack if type(hay) in (str, unicode)] | |
return get_close_matches(needle, haystack, n, cutoff) | |
elif type(needle) in (int, long, float, Decimal): | |
needle = Decimal(needle) | |
haystack = dict([(Decimal(hay), hay) for hay in haystack if type(hay) in (int, long, float, Decimal)]) | |
return [haystack[key] for key in sorted([hay for hay in haystack.keys() if (min(needle, hay) / max(needle, hay)) > cutoff], key=lambda hay: abs(hay - needle))[0:n]] | |
elif type(needle) == tuple: | |
needle = ''.join(needle) | |
haystack = dict([(''.join(hay), hay) for hay in haystack if type(hay) == tuple]) | |
return [haystack[key] for key in get_close_matches(needle, haystack.keys(), n, cutoff)] | |
else: | |
needle = hash(needle) | |
haystack = dict([(hash(hay), hay) for hay in haystack if type(hay) not in (str, unicode, int, long, float, Decimal, tuple)]) | |
return [haystack[key] for key in get_close_matches(needle, haystack.keys(), n, cutoff)] | |
if __name__ == '__main__': | |
roget = Thesaurus() | |
roget['tool'] = 'screwdriver' | |
roget['pool'] = 'water' | |
roget[('tweedle', 'dee')] = 'battle' | |
roget[('tweedle', 'dum')] = 'rattle' | |
roget[6] = 'at sixes' | |
roget[7] = 'and sevens' | |
print roget.keys() # [('tweedle', 'dum'), 6, 7, ('tweedle', 'dee'), 'tool', 'pool'] | |
print roget.values() # ['rattle', 'all sixes', 'and sevens', 'battle', 'screwdriver', 'water'] | |
print roget['tool'] # water | |
print roget['fool'] # screwdriver | |
print roget[('tweedle', 'dee')] # rattle | |
print roget[6] # and sevens | |
print roget['moronic'] # KeyError: 'moronic' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment