本文整理汇总了Python中difflib.get_close_matches方法的典型用法代码示例。如果您正苦于以下问题:Python difflib.get_close_matches方法的具体用法?Python difflib.get_close_matches怎么用?Python difflib.get_close_matches使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类difflib
的用法示例。
在下文中一共展示了difflib.get_close_matches方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_command
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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)
示例2: search_command
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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)
示例3: _check_value
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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)
示例4: _guess_radii_from_masses
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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
示例5: search
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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
示例6: _open_job_by_id
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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))
示例7: retrive_definition
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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
示例8: resolve_command
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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)
示例9: _get_first_word
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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
示例10: __str__
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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__()
示例11: check_base_type
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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()))))
示例12: check_monitoring
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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, ""
示例13: resolve_command
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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)
示例14: find_closest_match
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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]
示例15: _check_value
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import get_close_matches [as 别名]
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))