languages.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -- encoding: UTF-8 --
  2. from babel.core import get_global
  3. def get_official_languages(territory, regional=False, de_facto=False):
  4. """
  5. Get the official language(s) for the given territory.
  6. The language codes, if any are known, are returned in order of descending popularity.
  7. If the `regional` flag is set, then languages which are regionally official are also returned.
  8. If the `de_facto` flag is set, then languages which are "de facto" official are also returned.
  9. .. warning:: Note that the data is as up to date as the current version of the CLDR used
  10. by Babel. If you need scientifically accurate information, use another source!
  11. :param territory: Territory code
  12. :type territory: str
  13. :param regional: Whether to return regionally official languages too
  14. :type regional: bool
  15. :param de_facto: Whether to return de-facto official languages too
  16. :type de_facto: bool
  17. :return: Tuple of language codes
  18. :rtype: tuple[str]
  19. """
  20. territory = str(territory).upper()
  21. allowed_stati = {"official"}
  22. if regional:
  23. allowed_stati.add("official_regional")
  24. if de_facto:
  25. allowed_stati.add("de_facto_official")
  26. languages = get_global("territory_languages").get(territory, {})
  27. pairs = [
  28. (info['population_percent'], language)
  29. for language, info in languages.items()
  30. if info.get('official_status') in allowed_stati
  31. ]
  32. pairs.sort(reverse=True)
  33. return tuple(lang for _, lang in pairs)
  34. def get_territory_language_info(territory):
  35. """
  36. Get a dictionary of language information for a territory.
  37. The dictionary is keyed by language code; the values are dicts with more information.
  38. The following keys are currently known for the values:
  39. * `population_percent`: The percentage of the territory's population speaking the
  40. language.
  41. * `official_status`: An optional string describing the officiality status of the language.
  42. Known values are "official", "official_regional" and "de_facto_official".
  43. .. warning:: Note that the data is as up to date as the current version of the CLDR used
  44. by Babel. If you need scientifically accurate information, use another source!
  45. .. note:: Note that the format of the dict returned may change between Babel versions.
  46. See https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html
  47. :param territory: Territory code
  48. :type territory: str
  49. :return: Language information dictionary
  50. :rtype: dict[str, dict]
  51. """
  52. territory = str(territory).upper()
  53. return get_global("territory_languages").get(territory, {}).copy()