def match_fuzzy(needles, haystack, ignore_case=False, threshold=0.6): """ Performs an approximate match with the last needle against the end of every path past an acceptable threshold. For example: needles = ['foo', 'bar'] haystack = [ (path='/foo/bar/baz', weight=11), (path='/foo/baz/moo', weight=10), (path='/moo/foo/baz', weight=10), (path='/foo/baz', weight=10), (path='/foo/bar', weight=10), ] result = [ (path='/foo/bar/baz', weight=11), (path='/moo/foo/baz', weight=10), (path='/foo/baz', weight=10), (path='/foo/bar', weight=10), ] This is a weak heuristic and used as a last resort to find matches. """ end_dir = lambda path: last(os.path.split(path)) if ignore_case: needle = last(needles).lower() match_percent = lambda entry: SequenceMatcher(a=needle, b=end_dir(entry.path.lower())).ratio() else: needle = last(needles) match_percent = lambda entry: SequenceMatcher(a=needle, b=end_dir(entry.path)).ratio() meets_threshold = lambda entry: match_percent(entry) >= threshold return ifilter(meets_threshold, haystack)
def match_fuzzy(needles, haystack, ignore_case=False, threshold=0.6): """ Performs an approximate match with the last needle against the end of every path past an acceptable threshold. For example: needles = ['foo', 'bar'] haystack = [ (path='/foo/bar/baz', weight=11), (path='/foo/baz/moo', weight=10), (path='/moo/foo/baz', weight=10), (path='/foo/baz', weight=10), (path='/foo/bar', weight=10), ] result = [ (path='/foo/bar/baz', weight=11), (path='/moo/foo/baz', weight=10), (path='/foo/baz', weight=10), (path='/foo/bar', weight=10), ] This is a weak heuristic and used as a last resort to find matches. """ end_dir = lambda path: last(os.path.split(path)) if ignore_case: needle = last(needles).lower() match_percent = lambda entry: SequenceMatcher( a=needle, b=end_dir(entry.path.lower()), ).ratio() else: needle = last(needles) match_percent = lambda entry: SequenceMatcher( a=needle, b=end_dir(entry.path), ).ratio() meets_threshold = lambda entry: match_percent(entry) >= threshold return ifilter(meets_threshold, haystack)
def test_last(self): assert_equal(last(xrange(4)), 3) assert_equal(last([]), None)
def test_last(): assert last(xrange(4)) == 3 assert last([]) is None