Skip to content

Instantly share code, notes, and snippets.

@marazmiki
Created December 8, 2021 07:14
Show Gist options
  • Save marazmiki/5c3dbfbcee5197e761889aa7ecfa4b7f to your computer and use it in GitHub Desktop.
Save marazmiki/5c3dbfbcee5197e761889aa7ecfa4b7f to your computer and use it in GitHub Desktop.
import re
class AcceptLanguage:
__regex = re.compile(r";q=([\d.]+),?", re.I)
__jail = object()
@classmethod
def parse(cls, string: str) -> "AcceptLanguage":
instance = cls(cls.__jail, string)
instance.__do_parse()
return instance
def __do_parse(self):
bits = self.split()
self.__results = {
language: probability
for language_set, probability in zip(bits[::2], bits[1::2])
for language in language_set.split(",")
}
def __init__(self, jail, value):
if jail is not AcceptLanguage.__jail:
raise TypeError("Please use AcceptLanguage.parse() method instead")
self.__string = value
self.__results = {}
def split(self) -> list[str]:
return [item for item in self.__regex.split(self.__string) if item]
def get_results(self) -> dict[str, str]:
return self.__results
def get_highly_likely(self):
return max(self.__results, key=self.__results.get)
# Use case:
al_string = "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6,zh;q=0.5"
res = AcceptLanguage(al_string)
assert res.get_results() == {"ru-RU": "0.9", "ru": "0.9", "en-US": "0.8", "en": "0.7", "zh-CN": "0.6", "zh": "0.5"}
assert res.get_highly_likely() == "ru-RU"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment