2013年1月3日星期四

Google Currency Converter

繼上次check股價的Google Finance後,今次隆重推出Google Currency Converter如下,

import sys
import urllib.request as ur

currency_dict = {'CLP': 'Chilean Peso (CLP)', 'NPR': 'Nepalese Rupee (NPR)',
                 'HKD': 'Hong Kong Dollar (HKD)', 'LKR': 'Sri Lankan Rupee (LKR)',
                 'TWD': 'New Taiwan Dollar (TWD)', 'NOK': 'Norwegian Krone (NOK)',
                 'MKD': 'Macedonian Denar (MKD)', 'DZD': 'Algerian Dinar (DZD)',
                 'PLN': 'Polish Zloty (PLN)', 'BND': 'Brunei Dollar (BND)',
                 'CHF': 'Swiss Franc (CHF)', 'MVR': 'Maldivian Rufiyaa (MVR)',
                 'DKK': 'Danish Krone (DKK)', 'INR': 'Indian Rupee (INR)',
                 'KWD': 'Kuwaiti Dinar (KWD)', 'DOP': 'Dominican Peso (DOP)',
                 'UGX': 'Ugandan Shilling (UGX)', 'UZS': 'Uzbekistan Som (UZS)',
                 'PHP': 'Philippine Peso (PHP)', 'HUF': 'Hungarian Forint (HUF)',
                 'PGK': 'Papua New Guinean Kina (PGK)', 'IDR': 'Indonesian Rupiah (IDR)',
                 'RON': 'Romanian Leu (RON)', 'MDL': 'Moldovan Leu (MDL)',
                 'SLL': 'Sierra Leonean Leone (SLL)',
                 'AED': 'United Arab Emirates Dirham (AED)',
                 'VND': 'Vietnamese Dong (VND)', 'SGD': 'Singapore Dollar (SGD)',
                 'SKK': 'Slovak Koruna (SKK)', 'NIO': 'Nicaraguan Cordoba (NIO)',
                 'TND': 'Tunisian Dinar (TND)', 'FJD': 'Fijian Dollar (FJD)',
                 'XOF': 'CFAFranc BCEAO (XOF)', 'KYD': 'Cayman Islands Dollar (KYD)',
                 'BRL': 'Brazilian Real (BRL)', 'SCR': 'Seychellois Rupee (SCR)',
                 'PKR': 'Pakistani Rupee (PKR)', 'USD': 'US Dollar (USD)',
                 'NGN': 'Nigerian Naira (NGN)', 'CNY': 'Chinese Yuan (CNY)',
                 'NAD': 'Namibian Dollar (NAD)', 'ZAR': 'South African Rand (ZAR)',
                 'GBP': 'British Pound Sterling (GBP)', 'CRC': 'Costa Rican Colon (CRC)',
                 'JPY': 'Japanese Yen (JPY)', 'BHD': 'Bahraini Dinar (BHD)',
                 'PYG': 'Paraguayan Guarani (PYG)', 'EEK': 'Estonian Kroon (EEK)',
                 'LVL': 'Latvian Lats (LVL)', 'RUB': 'Russian Ruble (RUB)',
                 'AUD': 'Australian Dollar (AUD)', 'MAD': 'Moroccan Dirham (MAD)',
                 'NZD': 'New Zealand Dollar (NZD)', 'HRK': 'Croatian Kuna (HRK)',
                 'LBP': 'Lebanese Pound (LBP)', 'TRY': 'Turkish Lira (TRY)',
                 'ILS': 'Israeli New Sheqel (ILS)', 'KZT': 'Kazakhstani Tenge (KZT)',
                 'BDT': 'Bangladeshi Taka (BDT)', 'MXN': 'Mexican Peso (MXN)',
                 'ANG': 'Netherlands Antillean Guilder (ANG)',
                 'KRW': 'South Korean Won (KRW)', 'KES': 'Kenyan Shilling (KES)',
                 'ZMK': 'Zambian Kwacha (ZMK)', 'VEF': 'Venezuelan Bolivar (VEF)',
                 'TZS': 'Tanzanian Shilling (TZS)', 'HNL': 'Honduran Lempira (HNL)',
                 'JOD': 'Jordanian Dinar (JOD)', 'TTD': 'Trinidad and Tobago Dollar (TTD)',
                 'JMD': 'Jamaican Dollar (JMD)', 'COP': 'Colombian Peso (COP)',
                 'CAD': 'Canadian Dollar (CAD)', 'MYR': 'Malaysian Ringgit (MYR)',
                 'PEN': 'Peruvian NuevoSol (PEN)', 'THB': 'Thai Baht (THB)',
                 'SEK': 'Swedish Krona (SEK)', 'LTL': 'Lithuanian Litas (LTL)',
                 'RSD': 'Serbian Dinar (RSD)', 'BWP': 'Botswanan Pula (BWP)',
                 'EGP': 'Egyptian Pound (EGP)', 'UAH': 'Ukrainian Hryvnia (UAH)',
                 'EUR': 'Euro (EUR)', 'BOB': 'Bolivian Boliviano (BOB)',
                 'SVC': 'Salvadoran Colon (SVC)', 'OMR': 'Omani Rial (OMR)',
                 'YER': 'Yemeni Rial (YER)', 'QAR': 'Qatari Rial (QAR)',
                 'UYU': 'Uruguayan Peso (UYU)', 'SAR': 'Saudi Riyal (SAR)',
                 'MUR': 'Mauritian Rupee (MUR)', 'BGN': 'Bulgarian Lev (BGN)',
                 'CZK': 'Czech Republic Koruna (CZK)', 'ARS': 'Argentine Peso (ARS)'}

def get_currency(n, f, t):
    l = (f.upper(), t.upper())
    for i in l:
        if i not in currency_dict:
            raise ValueError('Invalid currency code {}'.format(i))
    url = 'https://www.google.com/ig/calculator?hl=en&q={}{}=?{}'.format(n, *l)
    s = ur.urlopen(url).read().replace(b'\xa0', b'').decode("utf-8")[1:-1].split(',')
    _, lv = s[0].split(':')
    _, rv = s[1].split(':')
    return lv.lstrip()[1:-1], rv.lstrip()[1:-1]

if __name__ == '__main__':
    if len(sys.argv) < 4:
        print('Usage: {} amount from to'.format(sys.argv[0]))
        sys.exit(-1)
    try:
        print('{} = {}'.format(*get_currency(*sys.argv[1:])))
    except ValueError as e:
        print(e.args)
        print('No such currency, please use following list of known currency.')
        for i in sorted(currency_dict.values()):
            print(i)
        sys.exit(-2)

但今次這個API return並不是標準的JSON string,key是沒有quote的,所以不能用Python built-in 的json library parse,但當然不想自行subclass一個JSONDecoder只為了decode一行string,所以自行string split算了。

除Python外,另有網上版以供選擇。

沒有留言:

發佈留言