将语言代码与此语言为官方语言或常用语言的国家/地区匹配

jac*_*ack 6 python localization country-codes

是否有任何python库可以获取特定语言代码的国家/地区列表,它是官方语言或常用语言?

例如,"fr"的语言代码与29个国家相关联,其中法语是官方语言加上常用的8个国家.

Ane*_*pic 14

尽管已经接受了答案,但据我所知,pycountry下面的xml文件都没有包含将语言映射到国家/地区的方法.它包含语言列表及其iso代码,国家列表及其iso代码,以及其他有用的东西,但不是.

同样地,Babel包很棒,但经过一段时间的挖掘后,我找不到任何方法来列出特定国家的所有语言.您可以做的最好的是"最有可能"的语言:https://stackoverflow.com/a/22199367/202168

所以我必须自己搞定......

def get_territory_languages():
    import lxml
    import urllib

    langxml = urllib.urlopen('http://unicode.org/repos/cldr/trunk/common/supplemental/supplementalData.xml')
    langtree = lxml.etree.XML(langxml.read())

    territory_languages = {}
    for t in langtree.find('territoryInfo').findall('territory'):
        langs = {}
        for l in t.findall('languagePopulation'):
            langs[l.get('type')] = {
                'percent': float(l.get('populationPercent')),
                'official': bool(l.get('officialStatus'))
            }
        territory_languages[t.get('type')] = langs
    return territory_languages
Run Code Online (Sandbox Code Playgroud)

您可能希望将其结果存储在文件中,而不是每次需要时都通过Web调用.

此数据集还包含"非官方"语言,您可能不想包含这些语言,这里有一些示例代码:

TERRITORY_LANGUAGES = get_territory_languages()

def get_official_locale_ids(country_code):
    country_code = country_code.upper()
    langs = TERRITORY_LANGUAGES[country_code].items()
    # most widely-spoken first:
    langs.sort(key=lambda l: l[1]['percent'], reverse=True)
    return [
        '{lang}_{terr}'.format(lang=lang, terr=country_code)
        for lang, spec in langs if spec['official']
    ]

get_official_locale_ids('es')
>>> ['es_ES', 'ca_ES', 'gl_ES', 'eu_ES', 'ast_ES']
Run Code Online (Sandbox Code Playgroud)


Joh*_*hin 5

寻找Babel包.它有一个每个支持的语言环境的pickle文件.请参阅localedata模块中的list()函数以获取所有语言环境的列表.然后编写一些代码将语言环境拆分为(语言,国家)等


dou*_*oug -2

pycountry(认真的)。您可以从包索引中获取它。

  • 我刚刚查看了它的文档,似乎您无法提供语言代码并获取使用该语言的所有国家/地区的列表 (7认同)