From: <gea...@us...> - 2009-05-26 21:18:04
|
Revision: 350 http://mypyspace.svn.sourceforge.net/mypyspace/?rev=350&view=rev Author: gearmonkey Date: 2009-05-26 21:18:00 +0000 (Tue, 26 May 2009) Log Message: ----------- forgot to add this custom dictionary I made for the weight loader... Added Paths: ----------- graphRDF/branches/songsAsNodes/rightDict.py Added: graphRDF/branches/songsAsNodes/rightDict.py =================================================================== --- graphRDF/branches/songsAsNodes/rightDict.py (rev 0) +++ graphRDF/branches/songsAsNodes/rightDict.py 2009-05-26 21:18:00 UTC (rev 350) @@ -0,0 +1,78 @@ +""" + +This is a simple extension of dict so that when you look for a string key, if it is not found as an exact match it will look for any key that contains the search string as an exact substring returnign the first it finds. +------- +I'm changing the _search to do a simple contains test and return on true. This will effectively perform a *value* match and return the first, if the exact match fails... +""" + +__revision__ = "$Rev$" + + + +class rightDict(dict): + "Provides a dictionary that performs fuzzy lookup" + def __init__(self, items = None): + """Construct a new rightDict instance + + items is an dictionary to copy items from (optional) + """ + super(rightDict, self).__init__() + + if items: + self.update(items) + + # short wrapper around some super (dict) methods + self._dict_contains = lambda key: \ + super(rightDict,self).__contains__(key) + + self._dict_getitem = lambda key: \ + super(rightDict,self).__getitem__(key) + + def _search(self, lookfor, stop_on_first = False): + """Returns the first value whose key contains lookfor + + """ + + # if the item is in the dictionary then just return it + if self._dict_contains(lookfor): + return True, lookfor, self._dict_getitem(lookfor), 1 + + + for key in self: + + # if the current key is not a string + # then we just skip it + try: + # perform the test: + if lookfor in key: + return (True, key, self._dict_getitem(key)) + except TypeError: + continue + + + #if we got through the loop there was no match. + return ( + False, + lookfor, + lookfor) + + + def __contains__(self, item): + "Overides Dictionary __contains__ to use fuzzy matching" + if self._search(item, True)[0]: + return True + else: + return False + + def __getitem__(self, lookfor): + "Overides Dictionary __getitem__ to use fuzzy matching" + matched, key, item = self._search(lookfor) + + if not matched: + raise KeyError( + "'%s' was not contained in any key."% + (str(lookfor))) + + return item + + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |