def get_completions(self, document, complete_event): text_before_cursor = document.current_line_before_cursor text_before_cursor_stripped = text_before_cursor.lstrip() if " " in text_before_cursor: # We got past the command and start looking for radio stations stripped_len = len(text_before_cursor) - len( text_before_cursor_stripped) command = text_before_cursor.split()[0] if command in self.commands: offset_stations_string = stripped_len + len( command) + 1 # Adds 1 to skip space after command. search_for = text_before_cursor[offset_stations_string:] matches = fuzzyfinder(search_for, list(self.stations)) for m in matches: yield Completion( m, -(document.cursor_position - offset_stations_string), display_meta=self.stations[m]) else: word_before_cursor = document.get_word_before_cursor(WORD=True) matches = fuzzyfinder(word_before_cursor, self.commands) for m in matches: yield Completion(m, start_position=-len(word_before_cursor))
def get_completions(self, document, complete_event, smart_completion=None): word_before_cursor = document.get_word_before_cursor(WORD=True) cmdline = shell_cmd_from_user_input( document.text_before_cursor.strip()) try: tokens = shlex.split(cmdline) for suffix, suggestor in self.end_to_suggestor.items(): if (tokens and not word_before_cursor and tokens[-1] == suffix or len(tokens) > 1 and tokens[-2] == suffix): for key in fuzzyfinder(word_before_cursor, suggestor()): yield Completion(key, -len(word_before_cursor), display=key) return _, _, suggestions = self.parser.parse_tokens(tokens) valid_keys = fuzzyfinder(word_before_cursor, suggestions.keys()) for key in valid_keys: yield Completion(key, -len(word_before_cursor), display=key, display_meta=suggestions[key]) except ValueError: pass
def parse_string(self): these_tags = [b.strip() for b in self.search_box.get().split(',')] # display found tag according to the latest input string # search using fuzzyfinder self.list_box.delete(0, END) [self.list_box.insert(END, a) for a in fuzzyfinder(these_tags[-1], self.tags)]
def get_completions(self, document, complete_event): word_before_cursor = document.get_word_before_cursor(WORD=True) words = list( filter(lambda item: "__" not in item, self.key_words.keys())) matches = fuzzyfinder(word_before_cursor, words) for m in matches: yield Completion(m, start_position=-len(word_before_cursor))
def get_completions(self, document, complete_event): sql_gen.logger.debug("Running get_completing within SuggestionCompleter") word_before_cursor = document.get_word_before_cursor(WORD=True) matches = fuzzyfinder(word_before_cursor, self.suggestions) for m in matches: yield Completion(m, start_position=-len(word_before_cursor)) sql_gen.logger.debug("Finished get_completing within SuggestionCompleter")
def dantafind(): """Search for patients in Danta study.""" file = "D:\\JOHN TILLET\\episode_data\\dantapolypdata.csv" with open(file, "r") as h: reader = csv.reader(h, delimiter=",") pat_list = [p[0].lower() for p in reader] clear() while True: print() query_string = input("Name in lower case, q to quit: ") if query_string == "q": break if query_string == "": clear() continue try: suggestions = fuzzyfinder(query_string, pat_list) suggestions = sorted(list(suggestions), key=lambda x: x.split()[-1]) clear() if not suggestions: print("No one here.") else: for p in suggestions: print(p) except UnicodeDecodeError: print("Try another list of letters!") continue
def apply_filter(self, filter): self.file_filter = filter if filter: self.filtered_files = list(fuzzyfinder(filter, self.shown_files, accessor=lambda x: x['file'].name)) else: self.filtered_files = self.shown_files[:]
def dantafind(): """Fuzzy search for patients in Danta study.""" file = 'D:\\JOHN TILLET\\episode_data\\dantapolypdata.csv' with open(file, 'r') as h: reader =csv.reader(h, delimiter=',') pat_list = [p[0].lower() for p in reader] clear() while True: print() query_string = input('Name in lower case, q to quit: ') if query_string == 'q': break if query_string == '': clear() continue try: suggestions = fuzzyfinder(query_string, pat_list) suggestions = sorted( list(suggestions), key= lambda x: x.split()[-1]) clear() if not suggestions: print('No one here.') else: for p in suggestions: print(p) except UnicodeDecodeError: print('Try another list of letters!') continue
def find_task(self, query): if isinstance(query, list): query = ' '.join(query) matches = fuzzyfinder(query, self.todo) try: return next(matches) except StopIteration: raise TymeError('No matching task found.')
def _no_query_found_error(self, item): suggestions = list(fuzzyfinder(item, self.dict.keys())) no_query_defined = "No query defined called '" + item + "'." if not suggestions: return no_query_defined else: return no_query_defined + " Did you mean?\n" + "\n".join( suggestions)
def parse_project(s): matches = list(fuzzyfinder(s.lower(), projects.keys())) if not matches: raise ValueError('Could not find a project matching "{}"'.format(s)) if len(matches) > 1: print('WARNING: found multiple matches for project "{}": {}'.format( s, matches)) return projects[matches[0]]
def get_completions(self, document, complete_event): word_before_cursor = document.get_word_before_cursor(WORD=False) #relation_type #print(bots) matches = fuzzyfinder(word_before_cursor, bots) #print(word_before_cursor) for m in matches: yield Completion(m, start_position=-len(word_before_cursor))
def text_changed(self): search_string = self.input_line.text() if search_string: self.fuzzy_items = list( fuzzyfinder(search_string, self.item_dict.keys()))[:self.max_items] else: self.fuzzy_items = list(self.item_dict.keys())[:self.max_items] self.update_listbox()
def fuzzy_match_by_key(keyword): keyword = "".join(keyword.split()) print(keyword) history_filter.append(keyword) searched_items = fuzzyfinder(keyword, what_str) searched_items = list(searched_items) #searched_items.sort(key=lambda x: len(x)) searched_items.sort(key=lambda x: len(x), reverse=True) return searched_items
def get_completions(self, document, complete_event): word = document.get_word_before_cursor(WORD=True) suggestions = fuzzyfinder(word, KEYWORDS + FUNCTIONS) for s in suggestions: if s in KEYWORDS: yield Completion(s, -len(word), display_meta='keyword') elif s in FUNCTIONS: yield Completion(s, -len(word), display_meta='function')
def main(): fn = os.path.join(os.path.dirname(__file__), 'patients.py') with open(fn, 'rb') as patpick: pat_list = pickle.load(patpick) while True: query_string = input('Name in lower case, q to quit: ') if query_string == 'q': break suggestions = fuzzyfinder(query_string, pat_list) print(list(suggestions))
def test_accessor(dict_collection): text = 'user' results = fuzzyfinder(text, dict_collection, lambda x: x['name']) expected = [{ 'name': 'user_group.doc' }, { 'name': 'users.txt' }, { 'name': 'api_user.doc' }] assert list(results) == expected
def search(name): # 按照名字在数据库中查找与name相匹配的名字。利用正则表达式实现模糊查询。 """ :param name: 模糊查询中需要输入的数据 :return:返回匹配的数据 """ query = "SELECT name FROM memberinfo" curs.execute(query) collection = curs.fetchall() collection = [info[0] for info in collection] text = name return list(fuzzyfinder.fuzzyfinder(name, collection))
def get_completions(self, document, complete_event, smart_completion=None): word_before_cursor = document.get_word_before_cursor(WORD=True) cmdline = document.text_before_cursor.strip() tokens = shlex.split(cmdline) _, _, suggestions = self.parser.parse_tokens(tokens) valid_keys = fuzzyfinder(word_before_cursor, suggestions.keys()) for key in valid_keys: yield Completion(key, -len(word_before_cursor), display=key, display_meta=suggestions[key])
def fzf(search_string: str): from fuzzyfinder import fuzzyfinder keys = [] tabs = {} for s in data: for k in data[s]: keys += [k] tabs[k] = data[s][k] suggestions = fuzzyfinder(search_string, keys) filtered_data = {x: tabs[x] for x in suggestions} return (filtered_data)
def get_object_settings(self, object_class): if (object_class in self.obj_settings): return self.obj_settings[object_class] # TODO: If there are no match object_class name then try to find the closest match using fuzzy find all_object_classes = list(self.obj_settings.keys()) fuzzy_object_classes = list( fuzzyfinder(object_class, all_object_classes)) if (len(fuzzy_object_classes) > 0): fuzzy_object_class = fuzzy_object_classes[0] # print("fuzzy_object_classes: {} - fuzzy_object_class: {}".format(fuzzy_object_classes, fuzzy_object_class)) return self.obj_settings[fuzzy_object_class] return None
def custom_edit_textChanged(self, event): # if event != '': try: rec = fuzzyfinder.fuzzyfinder(event, config.Stock_list.keys()) ui.listWidget.clear() if rec: for i in range(len(rec)): ui.listWidget.addItem(rec[i]) else: self.setText(event) except Exception: pass
def fuzzy_filter( search: str, schemas: List[dict], root_only: bool = False, key: str = "name_qual", fuzzy_keys: List[str] = FUZZY_SCHEMAS_KEYS, **kwargs, ) -> List[dict]: """Perform a fuzzy search against a set of field schemas. Args: search: string to search for against the keys in fuzzy_keys schemas: field schemas to search through root_only: only search against schemas of root fields key: return the schema key value instead of the field schemas fuzzy_keys: list of keys to check search against in each field schema """ def do_skip(schema): is_details = schema["name"].endswith("_details") is_all = schema["name"] == "all" not_select = not schema.get("selectable", True) is_root = root_only and not schema["is_root"] if any( [schema in matches, is_details, is_all, not_select, is_root]): return True return False matches = [] for schema in schemas: if do_skip(schema): continue values = [schema[x] for x in fuzzy_keys] if any([search.strip().lower() in x for x in values]): matches.append(schema) if not matches: for schema in schemas: if do_skip(schema): continue values = [schema[x] for x in fuzzy_keys] if list(fuzzyfinder(search, values)): matches.append(schema) return [x[key] for x in matches] if key else matches
def get_completions(self, document, complete_event): word_before_cursor = document.get_word_before_cursor(WORD=True) matches = fuzzyfinder(word_before_cursor, SQLKeywords) for m in matches: yield Completion(m, start_position=-len(word_before_cursor)) while 1: user_input = prompt( u'SQL>', history=FileHistory('historyff.txt'), auto_suggest=AutoSuggestFromHistory(), completer=SQLCompleter(), lexer=SqlLexer, ) click.echo_via_pager(user_input)
def parse_deps(obj): if not obj: return ret = [] deps = ensure_list(obj) for dep in deps: matches = list(fuzzyfinder(dep.lower(), tasks.keys())) if not matches: raise ValueError('Could not find a task matching "{}"'.format(dep)) if len(matches) > 1: print('WARNING: found multiple matches for task "{}": {}'.format( dep, matches)) task_name = matches[0] ret.append(tasks[task_name]) return ret
def get_completions(self, document, complete_event): global currentFolder if not currentFolder == None: additionalKeys = [ f.properties['Title'] for f in currentFolder.folders ] else: additionalKeys = list() word_before_cursor = document.get_word_before_cursor(WORD=True) matches = fuzzyfinder(word_before_cursor, [*PNOkeywords, *additionalKeys]) for m in matches: yield pt.completion.Completion( m, start_position=-len(word_before_cursor))
def find_collection_matches(word, lst, fuzzy): """ Yield all matching names in list :param lst: collection :param word: string user typed :param fuzzy: boolean :return: iterable """ if fuzzy: for suggestion in fuzzyfinder.fuzzyfinder(word, lst): yield Completion(suggestion, -len(word)) else: for name in sorted(lst): if name.startswith(word) or not word: yield Completion(name, -len(word))
def find_collection_matches(word, options, fuzzy): if options is None: return [] if fuzzy: for suggestion in fuzzyfinder.fuzzyfinder(word, options, accessor=lambda x: x.name): yield Completion(suggestion.name, -len(word), display_meta=suggestion.desc) else: for option in sorted(options, key=lambda x: x.name): if option.name.startswith(word) or not word: yield Completion(option.name, -len(word), display_meta=option.desc)
def find_dictionary_matches(word, dic, fuzzy): """ Yield all matching names in dict :param dic: dict mapping name to display name :param word: string user typed :param fuzzy: boolean :return: iterable """ if fuzzy: for suggestion in fuzzyfinder.fuzzyfinder(word, dic.keys()): yield Completion(suggestion, -len(word), dic[suggestion]) else: for name in sorted(dic.keys()): if name.startswith(word) or not word: yield Completion(name, -len(word), dic[name])
def find_collection_matches(self, word, collection, fuzzy): """Yields all matching names in list. Args: * word: A string representing the word before the cursor. * collection: A collection of words to match. * fuzzy: A boolean that specifies whether to use fuzzy matching. Yields: A generator of prompt_toolkit's Completions. """ if fuzzy: for suggestion in fuzzyfinder.fuzzyfinder(word, collection): yield Completion(suggestion, -len(word)) else: for name in sorted(collection): if name.startswith(word) or not word: yield Completion(name, -len(word))
def get_completions(self, document, complete_event): word_before_cursor = document.get_word_before_cursor(WORD=False) currentLine = document.current_line if (" " in currentLine): options=[] if(currentLine[0:1]=='!'): global runOnServer runOnServer = False try: options=osOptions except: osCommands("") options=osOptions else: runOnServer = True options = runOptions matches = fuzzyfinder(word_before_cursor, options) for m in matches: yield Completion(m, start_position=-len(word_before_cursor))
def text_changed(self): search_string = self.input_line.text() if FILTER_WITH == "fuzzyfinder": if search_string: self.fuzzy_items = list( fuzzyfinder(search_string, self.item_dict.keys()))[:self.max_items] else: self.fuzzy_items = list(self.item_dict.keys())[:self.max_items] else: if not search_string: search_string = "" if FILTER_WITH == "slzk_mod": self.fuzzy_items = process_search_string_withStart( search_string, self.item_dict, self.max_items) elif FILTER_WITH == "slzk": self.fuzzy_items = process_search_string( search_string, self.item_dict, self.max_items) self.update_listbox()
def get_completions(self, document, complete_event): """Use fuzzyfinder for date completions. The fuzzyfind auto sorts by alpha so this is to show dates relative to the current date instead of by day of week. """ base = datetime.datetime.today() date_format = '%a, %Y-%m-%d' date_list = [(base - datetime.timedelta(days=x)).strftime(date_format) for x in range(0, 30)] word_before_cursor = document.text_before_cursor words = fuzzyfinder(word_before_cursor, date_list) def sort_by_date(date_str: str): return datetime.datetime.strptime(date_str, date_format) # Re-sort by date rather than day name words = sorted(words, key=sort_by_date, reverse=True) for x in words: yield Completion(x, -len(word_before_cursor))
def get_completions(self, document, complete_event): word_before_cursor = document.get_word_before_cursor(WORD=False) currentLine = document.current_line #diffrent logic is applied if there are commands spesified or the command starts with a ! if (" " in currentLine): options = [] if (currentLine[0:1] == '!'): global runOnServer runOnServer = False try: options = osOptions except: osCommands("") options = osOptions else: runOnServer = True options = runOptions #do matching to only load predictive text with what has currently been typed matches = fuzzyfinder(word_before_cursor, options) for m in matches: yield Completion(m, start_position=-len(word_before_cursor))
def test_substring_match_with_dot(collection): text = '.txt' results = fuzzyfinder(text, collection) expected = ['users.txt', 'accounts.txt'] assert list(results) == expected
def test_no_alpha_num_sort(): collection = ['zzfuz', 'nnfuz', 'aafuz', 'ttfuz', 'wow!', 'python'] text = 'fuz' results = fuzzyfinder(text, collection, sort_results=False) expected = ['zzfuz', 'nnfuz', 'aafuz', 'ttfuz'] assert list(results) == expected
def test_fuzzy_match_ranking(collection): text = 'mi' results = fuzzyfinder(text, collection) expected = ['migrations.py', 'django_migrations.py', 'django_admin_log.py'] assert list(results) == expected
def test_case_insensitive_substring_match(cased_collection): text = 'miGr' results = fuzzyfinder(text, cased_collection) expected = ['MIGRATIONS.py', 'migrations.doc', 'django_MiGRations.py'] assert list(results) == expected
def test_fuzzy_match_greedy(collection): text = 'user' results = fuzzyfinder(text, collection) expected = ['user_group.doc', 'users.txt', 'api_user.doc'] assert list(results) == expected
def test_use_shortest_match_if_matches_overlap(): collection_list = ['fuuz', 'fuz', 'fufuz'] text = 'fuz' results = fuzzyfinder(text, collection_list) expected = ['fuz', 'fufuz', 'fuuz'] assert list(results) == expected
def test_fuzzy_integer_input(collection): text = 123 results = fuzzyfinder(text, collection) expected = ['123.py', 'test123test.py'] assert list(results) == expected
def test_accessor(dict_collection): text = 'user' results = fuzzyfinder(text, dict_collection, lambda x: x['name']) expected = [{'name': 'user_group.doc'}, {'name': 'users.txt'}, {'name': 'api_user.doc'}] assert list(results) == expected
def comparison(self): suggestions = fuzzyfinder(self.var.get(), self.lista) return list(suggestions)