Skip to content

Instantly share code, notes, and snippets.

@kramred
Last active July 18, 2018 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kramred/b25a0eda206f83a8f07f0a289cdfacd1 to your computer and use it in GitHub Desktop.
Save kramred/b25a0eda206f83a8f07f0a289cdfacd1 to your computer and use it in GitHub Desktop.
import re
_locale_delim_re = re.compile(r'[_-]')
def _value_matches(value, item):
def _normalize(language):
# print "_locale_delim_re.split(language.lower()): " + str(_locale_delim_re.split(language.lower()))
return _locale_delim_re.split(language.lower())[0]
# print "item == '*': " + str(item == '*')
# print "_normalize(value): " + str(_normalize(value))
# print "_normalize(item): " + str(_normalize(item))
# print "item == '*' or _normalize(value) == _normalize(item): " + str(item == '*' or _normalize(value) ==_normalize(item))
return item == '*' or _normalize(value) == _normalize(item)
def best_match(self, matches, default=None):
"""Returns the best match from a list of possible matches based
on the quality of the client. If two items have the same quality,
the one is returned that comes first.
:param matches: a list of matches to check for
:param default: the value that is returned if none match
"""
best_quality = -1
result = default
for server_item in matches:
# print 'server_item: ' + str(server_item)
for client_item, quality in self:
# print 'client_item, quality: '+ str(client_item) +", " + str(quality)
if quality <= best_quality:
break
if _value_matches(server_item, client_item) \
and quality > 0:
best_quality = quality
result = server_item
return result
print "best_match_ex0: " + best_match([('de-AT',1),('de',.8)],['de','en','es'])
print "best_match_ex1: " + best_match([('de-AT',1),('de',.8)],['de-AT','en','es'])
print "best_match_ex2: " + best_match([('en-us',1)],['en', 'de'])
print "best_match_ex3: " + best_match([('en',1)],['en-us', 'de'])
@kramred
Copy link
Author

kramred commented May 10, 2017

output:
best_match_ex0: de
best_match_ex1: de-AT
best_match_ex2: en
best_match_ex3: en-us

@a-sanders
Copy link

a-sanders commented Jul 18, 2018

best_match([('de-LU', 1), ('de-DE', 0.7), ('en', 0.3)], ['en', 'de', 'de-DE'])
returns
'de'

but expected
'de-DE'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment