1# Copyright 2016 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import difflib
6
7
8def GetMostLikelyMatchedObject(objects, target_name,
9                               name_func=lambda x: x,
10                               matched_score_threshold=0.4):
11  """Matches objects whose names are most likely matched with target.
12
13  Args:
14    objects: list of objects to match.
15    target_name: name to match.
16    name_func: function to get object name to match. Default bypass.
17    matched_score_threshold: threshold of likelihood to match.
18
19  Returns:
20    A list of objects whose names are likely target_name.
21  """
22  def MatchScore(obj):
23    return difflib.SequenceMatcher(
24        isjunk=None, a=name_func(obj), b=target_name).ratio()
25  object_score = [(o, MatchScore(o)) for o in objects]
26  result = [x for x in object_score if x[1] > matched_score_threshold]
27  return [x[0] for x in sorted(result, key=lambda r: r[1], reverse=True)]
28