问题
I have a Python function which accepts an alpha2 country code and a price string, where the aim is to get the country's currency and use the currency.letter property of that currency to format the supplied price string using string interpolation.
The above works fine so far - yet it falls over when called with Germany as the country as follows:
>>> 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'
>>>
The pycountry.countries
collection does not contain a currency with a numeric of 276 (Germany's numeric) - yet it does contain the Euro. Any ideas as to what the way around this may be?
回答1:
Unfortunately, the country numeric code is NOT the same as the currency numeric. According to the ISO, "Where possible the 3 digit numeric code is the same as the numeric country code" - but this is obviously NOT possible for the Euro, which is shared by multiple countries.
The numeric for the Euro is 978, not 276; apparently pycountry doesn't provide a mapping between country numerics and currency numerics. Here's a link to the raw tables (in XML or XLS format) so you can roll your own, if you so desire... http://www.currency-iso.org/en/home/tables/table-a1.html
回答2:
Not my favorite solution, but it works. I needed a project-wide solution for this problem:
# 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'))
and in settings.py (incomplete list):
EUROPEAN_COUNTRIES = [
'DE', # Germany
'FR',
'ES',
'PT',
'IT',
'NL',
]
Calling the patched get
:
>>> from modules.core import pycountry_patch
>>> pycountry_patch.currencies.get(numeric='276').name
u'Euro'
来源:https://stackoverflow.com/questions/23461352/pycountry-currency-formatting-woes-for-de-alpha2-country-code