Robot Framework Integrated Development Environment (RIDE)
recommendations.py
Go to the documentation of this file.
1 # Copyright 2008-2015 Nokia Networks
2 # Copyright 2016- Robot Framework Foundation
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 import difflib
17 
18 
20 
21  def __init__(self, normalizer=None):
22  self.normalizernormalizer = normalizer or (lambda x: x)
23 
24 
25  def find_recommendations(self, name, candidates, max_matches=10):
26  if not name or not candidates:
27  return []
28  norm_name = self.normalizernormalizer(name)
29  norm_candidates = self._get_normalized_candidates_get_normalized_candidates(candidates)
30  cutoff = self._calculate_cutoff_calculate_cutoff(norm_name)
31  norm_matches = difflib.get_close_matches(norm_name,
32  norm_candidates,
33  n=max_matches,
34  cutoff=cutoff)
35  return self._get_original_candidates_get_original_candidates(norm_candidates, norm_matches)
36 
37  @staticmethod
38 
46  def format_recommendations(msg, recommendations):
47  if recommendations:
48  msg += " Did you mean:"
49  for rec in recommendations:
50  msg += "\n %s" % rec
51  return msg
52 
53  def _get_normalized_candidates(self, candidates):
54  norm_candidates = {}
55  # sort before normalization for consistent Python/Jython ordering
56  for cand in sorted(candidates):
57  norm = self.normalizernormalizer(cand)
58  norm_candidates.setdefault(norm, []).append(cand)
59  return norm_candidates
60 
61  def _get_original_candidates(self, norm_candidates, norm_matches):
62  candidates = []
63  for norm_match in norm_matches:
64  candidates.extend(norm_candidates[norm_match])
65  return candidates
66 
67 
74  def _calculate_cutoff(self, string, min_cutoff=.5, max_cutoff=.85,
75  step=.03):
76  cutoff = min_cutoff + len(string) * step
77  return min(cutoff, max_cutoff)
def format_recommendations(msg, recommendations)
Add recommendations to the given message.
def _get_original_candidates(self, norm_candidates, norm_matches)
def find_recommendations(self, name, candidates, max_matches=10)
Return a list of close matches to name from candidates.
def _calculate_cutoff(self, string, min_cutoff=.5, max_cutoff=.85, step=.03)
Calculate a cutoff depending on string length.