PyCountry 'DE' Alpha2国家代码的货币格式问题
我有一个Python函数,它接受一个国家的alpha2代码和一个价格字符串,目的是获取该国家的货币,并使用这个货币的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(这是德国的数字代码)——但它确实包含了欧元。有没有人知道该怎么解决这个问题呢?
3 个回答
1
如果你想要一个完整的解决方案来获取某个国家或地区的货币符号,可以使用 babel.numbers.get_territory_currencies
这个功能。
http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.get_territory_currencies
1
这不是我最喜欢的解决办法,但它确实有效。我需要一个能在整个项目中都能用的解决方案来解决这个问题:
# 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'
4
很遗憾,国家的数字代码和货币的数字代码并不是一样的。根据国际标准化组织(ISO)的说法,“如果可能的话,3位数字的代码应该和国家的数字代码相同”,但这对欧元来说显然是不可能的,因为欧元是多个国家共同使用的。
欧元的数字代码是978,而不是276;显然,pycountry这个库并没有提供国家数字代码和货币数字代码之间的对应关系。如果你想自己处理,可以查看这个原始数据表(有XML或XLS格式): http://www.currency-iso.org/en/home/tables/table-a1.html