开发者

Python currency codes into a list

Does anyone have a nifty way to get all the three letter alphabetic currency codes (an example of the ones I mean is at http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm) into a list in Python 2.5? Note I don't want to do a screen scraping version as the code has to work offline - the website is just an example of the codes.

It looks like there should be a way using the locale library but it's not clear to me from reading the documentation and there must be a better way than copy pasting those into a file!

To clear the question up more, in C# for the same problem, the following code did it very neatly using the internal locale libraries:

Cu开发者_JS百科ltureInfo.GetCultures(CultureTypes.SpecificCultures)
          .Select(c => new RegionInfo(c.LCID).CurrencySymbol)
          .Distinct()

I was hoping there might be an equivalent in python. And thanks to everyone who has provided an answer so far.


Not very elegant or nifty, but you can generate the list once and save to use it later:

import urllib, re
url = "http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm"
print re.findall(r'\<td valign\="top"\>\s+([A-WYZ][A-Z]{2})\s+\</td\>', urllib.urlopen(url).read())

output:

['AFN', 'EUR', 'ALL', 'DZD', 'USD', 'EUR', 'AOA', 'ARS', 'AMD', 'AWG', 'AUD',
...
'UZS', 'VUV', 'EUR', 'VEF', 'VND', 'USD', 'USD', 'MAD', 'YER', 'ZMK', 'ZWL', 'SDR']

Note that you'll need to prune everything after X.. as they are apparently reserved names, which means that you'll get one rogue entry (SDR, the last element) which you can just delete by yourself.


You can get currency codes (and other) data from geonames. Here's some code that downloads the data (save the file locally to achieve the same result offline) and populates a list:

import urllib2

data = urllib2.urlopen('http://download.geonames.org/export/dump/countryInfo.txt')
ccodes = []
for line in data.read().split('\n'):
  if not line.startswith('#'):
    line = line.split('\t')
    try:
      if line[10]:
        ccodes.append(line[10])
    except IndexError:
      pass
ccodes = list(set(ccodes))
ccodes.sort()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜