【问题标题】:PyCountry currency formatting woes for 'DE' alpha2 country code'DE' alpha 2 国家代码的 PyCountry 货币格式字
【发布时间】:2014-05-04 20:45:24
【问题描述】:

我有一个 Python 函数,它接受 alpha2 国家代码和价格字符串,其目的是获取国家/地区的货币并使用该货币的 currency.letter 属性使用字符串插值来格式化提供的价格字符串。

到目前为止,上述工作正常 - 但是当以德国为国家/地区调用时,它会崩溃,如下所示:

>>> import pycountry
>>> country = pycountry.countries.get(alpha2='DE')
>>> currency = pycountry.currencies.get(numeric=country.numeric)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/pycountry/db.py", line 83, in get
    return self.indices[field][value]
KeyError: '276'
>>>

pycountry.countries 集合不包含数字为 276(德国数字)的货币 - 但它包含欧元。有什么想法可以解决这个问题吗?

【问题讨论】:

    标签: python currency-formatting


    【解决方案1】:

    如果您想要一个获取给定国家或地区货币符号的综合解决方案,您可以使用babel.numbers.get_territory_currencies

    http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.get_territory_currencies

    【讨论】:

      【解决方案2】:

      很遗憾,国家数字代码与货币数字不同。根据 ISO 的说法,“Where possible the 3 digit numeric code is the same as the numeric country code”——但这显然对于欧元来说是不可能的,因为欧元是由多个国家共享的。

      欧元的数字是 978,而不是 276;显然 pycountry 没有提供国家数字和货币数字之间的映射。这是原始表(XML 或 XLS 格式)的链接,因此您可以自己滚动,如果您愿意... http://www.currency-iso.org/en/home/tables/table-a1.html

      【讨论】:

        【解决方案3】:

        不是我最喜欢的解决方案,但它有效。我需要一个项目范围的解决方案来解决这个问题:

        # pycountry_patch.py
        from pycountry import db, countries, DATABASE_DIR, Currencies as pycountryCurrencies
        from django.conf import settings
        import os.path
        
        class Currencies(pycountryCurrencies):
            @db.lazy_load
            def get(self, **kw):
                assert len(kw) == 1, 'Only one criteria may be given.'
                field, value = kw.popitem()
        
                if field == 'numeric' and value in [countries.get(alpha2=x).numeric for x in settings.EUROPEAN_COUNTRIES]:
                    value = '978'
        
                return self.indices[field][value]
        
        currencies = Currencies(os.path.join(DATABASE_DIR, 'iso4217.xml'))
        

        在settings.py(不完整列表)中:

        EUROPEAN_COUNTRIES = [
            'DE',  # Germany
            'FR',
            'ES',
            'PT',
            'IT',
            'NL',
        ]
        

        调用打补丁的get

        >>> from modules.core import pycountry_patch
        >>> pycountry_patch.currencies.get(numeric='276').name
        u'Euro'
        

        【讨论】:

        • PS:此处使用欧元的国家列表并不完整。 Afaik 有 25 个国家/地区使用欧元。
        猜你喜欢
        • 2023-04-04
        • 1970-01-01
        • 2018-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多