Python difflib.get_close_matches() Examples
The following are 30
code examples of difflib.get_close_matches().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
difflib
, or try the search function
.
Example #1
Source File: off_topic_names.py From bot with MIT License | 11 votes |
def search_command(self, ctx: Context, *, query: OffTopicName) -> None: """Search for an off-topic name.""" result = await self.bot.api_client.get('bot/off-topic-channel-names') in_matches = {name for name in result if query in name} close_matches = difflib.get_close_matches(query, result, n=10, cutoff=0.70) lines = sorted(f"• {name}" for name in in_matches.union(close_matches)) embed = Embed( title="Query results", colour=Colour.blue() ) if lines: await LinePaginator.paginate(lines, ctx, embed, max_size=400, empty=False) else: embed.description = "Nothing found." await ctx.send(embed=embed)
Example #2
Source File: parser.py From knack with MIT License | 6 votes |
def _check_value(self, action, value): # Override to customize the error message when a argument is not among the available choices # converted value must be one of the choices (if specified) import difflib import sys if action.choices is not None and value not in action.choices: # parser has no `command_source`, value is part of command itself error_msg = "{prog}: '{value}' is not in the '{prog}' command group. See '{prog} --help'.".format( prog=self.prog, value=value) logger.error(error_msg) candidates = difflib.get_close_matches(value, action.choices, cutoff=0.7) if candidates: print_args = { 's': 's' if len(candidates) > 1 else '', 'verb': 'are' if len(candidates) > 1 else 'is', 'value': value } suggestion_msg = "\nThe most similar choice{s} to '{value}' {verb}:\n".format(**print_args) suggestion_msg += '\n'.join(['\t' + candidate for candidate in candidates]) print(suggestion_msg, file=sys.stderr) self.exit(2)
Example #3
Source File: tron_tools.py From paasta with Apache License 2.0 | 6 votes |
def check_monitoring(self) -> Tuple[bool, str]: monitoring = self.get_monitoring() valid_teams = list_teams() if monitoring is not None: team_name = monitoring.get("team", None) if team_name is None: return False, "Team name is required for monitoring" elif team_name not in valid_teams: suggest_teams = difflib.get_close_matches( word=team_name, possibilities=valid_teams ) return ( False, f"Invalid team name: {team_name}. Do you mean one of these: {suggest_teams}", ) return True, ""
Example #4
Source File: wrapper.py From pb_bss with MIT License | 6 votes |
def __str__(self): if len(self.args) == 2: item, keys = self.args import difflib # Suggestions are sorted by their similarity. suggestions = difflib.get_close_matches( item, keys, cutoff=0, n=100 ) return f'{item!r}.\n' \ f'Close matches: {suggestions!r}' elif len(self.args) == 3: item, keys, msg = self.args import difflib # Suggestions are sorted by their similarity. suggestions = difflib.get_close_matches( item, keys, cutoff=0, n=100 ) return f'{item!r}.\n' \ f'Close matches: {suggestions!r}\n' \ f'{msg}' else: return super().__str__()
Example #5
Source File: erairaws.py From anime-downloader with The Unlicense | 6 votes |
def search(cls, query): cls.bypass(cls) soup = helpers.soupify(helpers.get("https://erai-raws.info/anime-list/")) result_data = soup.find("div", {"class":"shows-wrapper"}).find_all("a") titles = [x.text.strip() for x in result_data] #Erai-raws doesnt have a search that I could find - so I've opted to implement it myself titles = get_close_matches(query, titles, cutoff=0.2) result_data = [x for x in result_data if x.text.strip() in titles] search_results = [ SearchResult( title = result.text.strip(), url = "https://erai-raws.info/anime-list/" + result.get("href") ) for result in result_data ] return search_results
Example #6
Source File: cfy.py From cloudify-cli with Apache License 2.0 | 6 votes |
def resolve_command(self, ctx, args): """Override clicks ``resolve_command`` method and appends *Did you mean ...* suggestions to the raised exception message. """ try: return super(AliasedGroup, self).resolve_command(ctx, args) except click.exceptions.UsageError as error: error_msg = str(error) original_cmd_name = click.utils.make_str(args[0]) matches = difflib.get_close_matches( original_cmd_name, self.list_commands(ctx), self.max_suggestions, self.cutoff) if matches: error_msg += '\n\nDid you mean one of these?\n {0}'.format( '\n '.join(matches)) raise click.exceptions.UsageError(error_msg, error.ctx)
Example #7
Source File: uorb_rtps_classifier.py From px4_ros_com with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_base_type(self): """ Check if alias message has correct base type """ registered_alias_msgs = list( dict['alias'] for dict in self.msg_id_map['rtps'] if 'alias' in list(dict.keys())) base_types = [] for dict in self.msg_id_map['rtps']: if 'alias' not in list(dict.keys()): base_types.append(dict['msg']) incorrect_base_types = list( set(registered_alias_msgs) - set(base_types)) base_types_suggestion = {} for incorrect in incorrect_base_types: base_types_suggestion.update({incorrect: difflib.get_close_matches( incorrect, base_types, n=1, cutoff=0.6)}) if len(base_types_suggestion) > 0: raise AssertionError( ('\n' + '\n'.join('\t- The multi-topic message base type \'{}\' does not exist.{}'.format(k, (' Did you mean \'' + v[0] + '\'?' if v else '')) for k, v in list(base_types_suggestion.items()))))
Example #8
Source File: __main__.py From signac with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _open_job_by_id(project, job_id): "Attempt to open a job by id and provide user feedback on error." try: return project.open_job(id=job_id) except KeyError: close_matches = difflib.get_close_matches( job_id, [jid[:len(job_id)] for jid in project.find_job_ids()]) msg = "Did not find job corresponding to id '{}'.".format(job_id) if len(close_matches) == 1: msg += " Did you mean '{}'?".format(close_matches[0]) elif len(close_matches) > 1: msg += " Did you mean any of [{}]?".format('|'.join(close_matches)) raise KeyError(msg) except LookupError: n = project.min_len_unique_id() raise LookupError("Multiple matches for abbreviated id '{}'. " "Use at least {} characters for guaranteed " "unique ids.".format(job_id, n))
Example #9
Source File: properties.py From pytim with GNU General Public License v3.0 | 6 votes |
def _guess_radii_from_masses(interface, group, guessed): radii = np.copy(group.radii) masses = group.masses types = group.types unique_masses = np.unique(masses) # Let's not consider atoms with zero mass. unique_masses = unique_masses[unique_masses > 0] d = atoms_maps for target_mass in unique_masses: atype, _ = min( d.items(), key=lambda __entry: abs(__entry[1]['mass'] - target_mass)) try: match_type = get_close_matches( atype, interface.radii_dict.keys(), n=1, cutoff=0.1) rd = interface.radii_dict radii[masses == target_mass] = rd[match_type[0]] for t in types[masses == target_mass]: guessed.update({t: rd[match_type[0]]}) except BaseException: pass group.radii = radii
Example #10
Source File: text_search.py From iris with Mozilla Public License 2.0 | 6 votes |
def _get_first_word(word, data_list): """Finds all occurrences of the first searched word.""" words_found = [] cutoff_type = ( "digit" if _replace_multiple(word, digit_chars, "").isdigit() else "string" ) for data in data_list: cutoff = cutoffs[cutoff_type]["max_cutoff"] while cutoff >= cutoffs[cutoff_type]["min_cutoff"]: if difflib.get_close_matches(word, [data[11]], cutoff=cutoff): try: vd = _create_rectangle_from_ocr_data(data, data[12]) if not _is_similar_result(words_found, vd.x, vd.y, WORD_PROXIMITY): words_found.append(vd) except ValueError: continue cutoff -= cutoffs[cutoff_type]["step"] return words_found
Example #11
Source File: common.py From KiPart with MIT License | 6 votes |
def find_closest_match(name, name_dict, fuzzy_match, threshold=0.0): """Approximate matching subroutine""" # Scrub non-alphanumerics from name and lowercase it. scrubber = re.compile("[\W.]+") name = scrubber.sub("", name).lower() # Return regular dictionary lookup if fuzzy matching is not enabled. if fuzzy_match == False: return name_dict[name] # Find the closest fuzzy match to the given name in the scrubbed list. # Set the matching threshold to 0 so it always gives some result. match = difflib.get_close_matches(name, list(name_dict.keys()), 1, threshold)[0] return name_dict[match]
Example #12
Source File: off_topic_names.py From bot with MIT License | 6 votes |
def add_command(self, ctx: Context, *, name: OffTopicName) -> None: """ Adds a new off-topic name to the rotation. The name is not added if it is too similar to an existing name. """ existing_names = await self.bot.api_client.get('bot/off-topic-channel-names') close_match = difflib.get_close_matches(name, existing_names, n=1, cutoff=0.8) if close_match: match = close_match[0] log.info( f"{ctx.author} tried to add channel name '{name}' but it was too similar to '{match}'" ) await ctx.send( f":x: The channel name `{name}` is too similar to `{match}`, and thus was not added. " "Use `!otn forceadd` to override this check." ) else: await self._add_name(ctx, name)
Example #13
Source File: __init__.py From pipenv with MIT License | 6 votes |
def resolve_command(self, ctx, args): """ Overrides clicks ``resolve_command`` method and appends *Did you mean ...* suggestions to the raised exception message. """ original_cmd_name = click.utils.make_str(args[0]) try: return super(DYMMixin, self).resolve_command(ctx, args) except click.exceptions.UsageError as error: error_msg = str(error) matches = difflib.get_close_matches(original_cmd_name, self.list_commands(ctx), self.max_suggestions, self.cutoff) if matches: error_msg += '\n\nDid you mean one of these?\n %s' % '\n '.join(matches) # pylint: disable=line-too-long raise click.exceptions.UsageError(error_msg, error.ctx)
Example #14
Source File: argparser.py From bash-lambda-layer with MIT License | 6 votes |
def _check_value(self, action, value): """ It's probably not a great idea to override a "hidden" method but the default behavior is pretty ugly and there doesn't seem to be any other way to change it. """ # converted value must be one of the choices (if specified) if action.choices is not None and value not in action.choices: msg = ['Invalid choice, valid choices are:\n'] for i in range(len(action.choices))[::self.ChoicesPerLine]: current = [] for choice in action.choices[i:i+self.ChoicesPerLine]: current.append('%-40s' % choice) msg.append(' | '.join(current)) possible = get_close_matches(value, action.choices, cutoff=0.8) if possible: extra = ['\n\nInvalid choice: %r, maybe you meant:\n' % value] for word in possible: extra.append(' * %s' % word) msg.extend(extra) raise argparse.ArgumentError(action, '\n'.join(msg))
Example #15
Source File: dictionary_5.py From Interactive-Dictionary-in-Python with MIT License | 6 votes |
def retrive_definition(word): #Removing the case-sensitivity from the program #For example 'Rain' and 'rain' will give same output #Converting all letters to lower because out data is in that format word = word.lower() #Check for non existing words #1st elif: To make sure the program return the definition of words that start with a capital letter (e.g. Delhi, Texas) #2nd elif: To make sure the program return the definition of acronyms (e.g. USA, NATO) if word in data: return data[word] elif word.title() in data: return data[word.title()] elif word.upper() in data: return data[word.upper()] #3rd elif: To find a similar word #-- len > 0 because we can print only when the word has 1 or more close matches #-- In the return statement, the last [0] represents the first element from the list of close matches elif len(get_close_matches(word, data.keys())) > 0: return ("Did you mean %s instead?" % get_close_matches(word, data.keys())[0]) #Input from user
Example #16
Source File: __init__.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
Example #17
Source File: __init__.py From learn_python3_spider with MIT License | 5 votes |
def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
Example #18
Source File: friction.py From fluids with MIT License | 5 votes |
def fuzzy_match(name, strings): global fuzzy_match_fun if fuzzy_match_fun is not None: return fuzzy_match_fun(name, strings) try: from fuzzywuzzy import process, fuzz fuzzy_match_fun = lambda name, strings: process.extractOne(name, strings, scorer=fuzz.partial_ratio)[0] except ImportError: # pragma: no cover import difflib fuzzy_match_fun = lambda name, strings: difflib.get_close_matches(name, strings, n=1, cutoff=0)[0] return fuzzy_match_fun(name, strings)
Example #19
Source File: ConfigManager.py From ProjectAlice with GNU General Public License v3.0 | 5 votes |
def getAliceConfigByName(self, configName: str, voiceControl: bool = False) -> typing.Any: return self._aliceConfigurations.get( configName, difflib.get_close_matches(word=configName, possibilities=self._aliceConfigurations, n=3) if voiceControl else '' )
Example #20
Source File: __init__.py From hacktoberfest2018 with GNU General Public License v3.0 | 5 votes |
def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
Example #21
Source File: __init__.py From stopstalk-deployment with MIT License | 5 votes |
def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
Example #22
Source File: ghost.py From ghost with Apache License 2.0 | 5 votes |
def list(self, key_name=None, max_suggestions=100, cutoff=0.5, locked_only=False, key_type=None): """Return a list of all keys. """ self._assert_valid_stash() key_list = [k for k in self._storage.list() if k['name'] != 'stored_passphrase' and (k.get('lock') if locked_only else True)] if key_type: # To maintain backward compatibility with keys without a type. # The default key type is secret, in which case we also look for # keys with no (None) types. types = ('secret', None) if key_type == 'secret' else [key_type] key_list = [k for k in key_list if k.get('type') in types] key_list = [k['name'] for k in key_list] if key_name: if key_name.startswith('~'): key_list = difflib.get_close_matches( key_name.lstrip('~'), key_list, max_suggestions, cutoff) else: key_list = [k for k in key_list if key_name in k] audit( storage=self._storage.db_path, action='LIST' + ('[LOCKED]' if locked_only else ''), message=json.dumps(dict())) return key_list
Example #23
Source File: __init__.py From hacktoberfest2018 with GNU General Public License v3.0 | 5 votes |
def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
Example #24
Source File: utils.py From pb_bss with MIT License | 5 votes |
def __getattr__(self, name): """ >>> from IPython.lib.pretty import pprint >>> from pb_bss.distribution.cacgmm import ( ... ComplexAngularCentralGaussian, ... CACGMM, ... ) >>> model = ComplexAngularCentralGaussian() >>> model.covariances Traceback (most recent call last): ... AttributeError: 'ComplexAngularCentralGaussian' object has no attribute 'covariances'. Close matches: ['covariance_eigenvalues', 'covariance_eigenvectors'] >>> model.abc Traceback (most recent call last): ... AttributeError: 'ComplexAngularCentralGaussian' object has no attribute 'abc'. Close matches: ['covariance_eigenvectors', 'covariance_eigenvalues'] """ import difflib similar = difflib.get_close_matches(name, self.__dataclass_fields__.keys()) if len(similar) == 0: similar = list(self.__dataclass_fields__.keys()) raise AttributeError( f'{self.__class__.__name__!r} object has no attribute {name!r}.\n' f'Close matches: {similar}' )
Example #25
Source File: kifield.py From KiField with MIT License | 5 votes |
def lc_get_close_matches(lbl, possibilities, num_matches=3, cutoff=0.6): '''Return list of closest matches to lbl from possibilities (case-insensitive).''' # Strip any non-strings so str.lower() doesn't crash. possibilities = [p for p in possibilities if isinstance(p, basestring)] if USING_PYTHON2: lc_lbl = str.lower(unicode(lbl)) lc_possibilities = [str.lower(unicode(p)) for p in possibilities] else: lc_lbl = str.lower(lbl) lc_possibilities = [str.lower(p) for p in possibilities] lc_matches = get_close_matches(lc_lbl, lc_possibilities, num_matches, cutoff) return [possibilities[lc_possibilities.index(m)] for m in lc_matches]
Example #26
Source File: utils.py From paasta with Apache License 2.0 | 5 votes |
def suggest_possibilities( word: str, possibilities: Iterable[str], max_suggestions: int = 3 ) -> str: suggestions = cast( List[str], difflib.get_close_matches( word=word, possibilities=set(possibilities), n=max_suggestions ), ) if len(suggestions) == 1: return f"\nDid you mean: {suggestions[0]}?" elif len(suggestions) >= 1: return f"\nDid you mean one of: {', '.join(suggestions)}?" else: return ""
Example #27
Source File: __init__.py From pipenv with MIT License | 5 votes |
def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
Example #28
Source File: price_comparison_engine.py From Amazon-Flipkart-Price-Comparison-Engine with MIT License | 5 votes |
def price_amzn(self,key): url_amzn = 'https://www.amazon.in/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=' + str(key) # Faking the visit from a browser headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} # Getting titles of all products on that page self.title_arr = [] self.opt_title = StringVar() source_code = requests.get(url_amzn, headers=self.headers) plain_text = source_code.text self.soup = BeautifulSoup(plain_text, "html.parser") for titles in self.soup.find_all('a', {'class': 'a-link-normal a-text-normal'}): try: self.title_arr.append(titles.img.get('alt')) except AttributeError: continue # Getting closest match of the input from user in titles user_input = self.var.get().title() self.matches_amzn = get_close_matches(user_input, self.title_arr, 20, 0.01) self.opt_title.set(self.matches_amzn[0]) product_block = self.soup.find(attrs= {'title': self.opt_title.get()}) self.product_link = product_block.get('href') product_source_code = requests.get(self.product_link, headers=headers) product_plain_text = product_source_code.text product_soup = BeautifulSoup(product_plain_text, "html.parser") try: for price in product_soup.find(attrs={'id': 'priceblock_ourprice'}): self.var_amzn.set(price) self.title_amzn_var.set(self.matches_amzn[0]) except TypeError: self.var_amzn.set('None') self.title_amzn_var.set('product not available')
Example #29
Source File: price_comparison_engine.py From Amazon-Flipkart-Price-Comparison-Engine with MIT License | 5 votes |
def price_flipkart(self,key): url_flip = 'https://www.flipkart.com/search?q=' + str(key) + '&marketplace=FLIPKART&otracker=start&as-show=on&as=off' self.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} title_arr = [] self.opt_title_flip = StringVar() source_code = requests.get(url_flip, headers=self.headers) plain_text = source_code.text self.soup_flip = BeautifulSoup(plain_text, "html.parser") for title in self.soup_flip.find_all('div', {'class': '_3wU53n'}): title_arr.append(title.text) user_input = self.var.get().title() self.matches_flip = get_close_matches(user_input, title_arr, 20, 0.1) try: self.opt_title_flip.set(self.matches_flip[0]) except IndexError: self.opt_title_flip.set('Product not found') try: for div in self.soup_flip.find_all('a', {'class': '_31qSD5'}): for each in div.find_all('div', {'class': '_3wU53n'}): if each.text == self.opt_title_flip.get(): self.link_flip ='https://www.flipkart.com' + div.get('href') product_source_code = requests.get(self.link_flip, headers=self.headers) product_plain_text = product_source_code.text product_soup = BeautifulSoup(product_plain_text, "html.parser") for price in product_soup.find_all('div', {'class': '_1vC4OE _3qQ9m1'}): self.var_flipkart.set(price.text[1:] + '.00') except UnboundLocalError: pass
Example #30
Source File: __init__.py From deepWordBug with Apache License 2.0 | 5 votes |
def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False