2014-05-04 53 views
3

我有一個Python函數,它接受一個alpha2國家代碼和一個價格字符串,其目的是獲取該國家的貨幣並使用該貨幣的currency.letter屬性使用字符串插值格式化提供的價格字符串PyCountry貨幣格式化困境'DE'alpha2國家代碼

上述工作正常至今 - 但在與德國被稱爲全國如下它倒下:

>>> 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數字(德國的數字) - 但它確實包含了歐元。任何想法可以解決這個問題?

回答

4

不幸的是,國家數字代碼與貨幣數字不一樣。根據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

0

不是我最喜歡的解決方案,但它的工作原理。我需要這個問題的項目範圍內的解決方案:

# 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' 
+0

PS:列表在這裏使用歐元的國家並不完整。阿法克有25個國家使用歐元。 – wp78de