Created
November 18, 2019 10:38
-
-
Save dre-hh/f763fb2a801cbad6aef1aeb49191acf4 to your computer and use it in GitHub Desktop.
Fuzzy finder from pgcli
This file contains hidden or 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
import re | |
from IPython import embed | |
import os | |
def fuzzyfinder(input, collection): | |
suggestions = [] | |
input = str(input) if not isinstance(input, str) else input | |
pat = '.*?'.join(map(re.escape, input)) | |
pat = '(?=({0}))'.format(pat) # lookahead regex to manage overlapping matches | |
regex = re.compile(pat, re.IGNORECASE) | |
print(regex) | |
for item in collection: | |
r = list(regex.finditer(item)) | |
# print('iter', item, r) | |
if r: | |
best = min(r, key=lambda x: len(x.group(1))) # find shortest match: | |
print('best', best.group(1), best) | |
suggestions.append((len(best.group(1)), best.start(), item)) | |
return sorted(suggestions)[:15] | |
def collection(): | |
return ['migrations.py', | |
'django_migrations.py', | |
'django_admin_log.py', | |
'api_user.doc', | |
'user_group.doc', | |
'users.txt', | |
'accounts.txt', | |
'123.py', | |
'test123test.py' | |
] | |
def files(): | |
ret = [] | |
for root, dirs, files in os.walk('.'): | |
for file in files: | |
path = os.path.join(root, file) | |
ret.append(path) | |
return ret | |
ret = fuzzyfinder("mipy", collection()) | |
print(ret) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment