Last active
October 27, 2016 03:21
-
-
Save fengdai/2205a02a168163bd924f170216323af8 to your computer and use it in GitHub Desktop.
currencycode.proto file generator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
# http://www.iso.org/iso/home/standards/currency_codes.htm | |
# http://www.currency-iso.org/dam/downloads/lists/list_one.xml | |
import requests | |
import xml.dom.minidom | |
def fetch_ISO_4217_XML_Str(): | |
url = 'http://www.currency-iso.org/dam/downloads/lists/list_one.xml' | |
result = requests.get(url) | |
return result.text | |
# [(currencyCode, currencyNumber)] | |
def currencylist(xmlStr): | |
dom = xml.dom.minidom.parseString(xmlStr) | |
ccyNtries = dom.documentElement.getElementsByTagName('CcyNtry') | |
l = [] | |
s = set() | |
for ccyNtry in ccyNtries: | |
ccyNodes = ccyNtry.getElementsByTagName('Ccy') | |
if ccyNodes.length > 0: | |
currencyCode = ccyNodes[0].childNodes[0].data | |
countryName = ccyNtry.getElementsByTagName( | |
'CtryNm')[0].childNodes[0].data | |
currencyName = ccyNtry.getElementsByTagName( | |
'CcyNm')[0].childNodes[0].data | |
currencyNumber = ccyNtry.getElementsByTagName( | |
'CcyNbr')[0].childNodes[0].data | |
if currencyCode not in s: | |
l.append((countryName, currencyName, | |
currencyCode, currencyNumber)) | |
s.add(currencyCode) | |
return l | |
def generateProtoFile(): | |
l = currencylist(fetch_ISO_4217_XML_Str()) | |
sortedList = sorted(l, key=byCurrencyCode) | |
with open('./currencycode.proto', 'w') as f: | |
f.writelines('// Generated by "currencycode.py":\n') | |
f.writelines( | |
'// https://gist.github.com/fengdai/2205a02a168163bd924f170216323af8\n\n') | |
f.writelines('syntax = "proto2";\n\n') | |
f.writelines('enum CurrencyCode {\n') | |
for countryName, currencyName, currencyCode, currencyNumber in sortedList: | |
f.writelines(' // %s -- %s\n' % (countryName, currencyName)) | |
f.writelines(' %s = %d;\n' % | |
(currencyCode, int(currencyNumber))) | |
f.writelines('}\n') | |
def byCurrencyCode(t): | |
return t[2].lower() | |
if __name__ == "__main__": | |
generateProtoFile() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment