fetch_currencies.py 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import re
  4. import unicodedata
  5. import string
  6. from urllib import urlencode
  7. from requests import get
  8. languages = {'de', 'en', 'es', 'fr', 'hu', 'it', 'nl', 'jp'}
  9. url_template = 'https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&{query}&props=labels%7Cdatatype%7Cclaims%7Caliases&languages=' + '|'.join(languages)
  10. url_wmflabs_template = 'http://wdq.wmflabs.org/api?q='
  11. url_wikidata_search_template = 'http://www.wikidata.org/w/api.php?action=query&list=search&format=json&srnamespace=0&srprop=sectiontitle&{query}'
  12. wmflabs_queries = [
  13. 'CLAIM[31:8142]', # all devise
  14. ]
  15. db = {
  16. 'iso4217': {
  17. },
  18. 'names': {
  19. }
  20. }
  21. def remove_accents(data):
  22. return unicodedata.normalize('NFKD', data).lower()
  23. def normalize_name(name):
  24. return re.sub(' +', ' ', remove_accents(name.lower()).replace('-', ' '))
  25. def add_currency_name(name, iso4217):
  26. global db
  27. db_names = db['names']
  28. if not isinstance(iso4217, basestring):
  29. print "problem", name, iso4217
  30. return
  31. name = normalize_name(name)
  32. if name == '':
  33. print "name empty", iso4217
  34. return
  35. iso4217_set = db_names.get(name, None)
  36. if iso4217_set is not None and iso4217 not in iso4217_set:
  37. db_names[name].append(iso4217)
  38. else:
  39. db_names[name] = [iso4217]
  40. def add_currency_label(label, iso4217, language):
  41. global db
  42. db['iso4217'][iso4217] = db['iso4217'].get(iso4217, {})
  43. db['iso4217'][iso4217][language] = label
  44. def get_property_value(data, name):
  45. prop = data.get('claims', {}).get(name, {})
  46. if len(prop) == 0:
  47. return None
  48. value = prop[0].get('mainsnak', {}).get('datavalue', {}).get('value', '')
  49. if value == '':
  50. return None
  51. return value
  52. def parse_currency(data):
  53. iso4217 = get_property_value(data, 'P498')
  54. if iso4217 is not None:
  55. unit = get_property_value(data, 'P558')
  56. if unit is not None:
  57. add_currency_name(unit, iso4217)
  58. labels = data.get('labels', {})
  59. for language in languages:
  60. name = labels.get(language, {}).get('value', None)
  61. if name is not None:
  62. add_currency_name(name, iso4217)
  63. add_currency_label(name, iso4217, language)
  64. aliases = data.get('aliases', {})
  65. for language in aliases:
  66. for i in range(0, len(aliases[language])):
  67. alias = aliases[language][i].get('value', None)
  68. add_currency_name(alias, iso4217)
  69. def fetch_data(wikidata_ids):
  70. url = url_template.format(query=urlencode({'ids': '|'.join(wikidata_ids)}))
  71. htmlresponse = get(url)
  72. jsonresponse = json.loads(htmlresponse.content)
  73. entities = jsonresponse.get('entities', {})
  74. for pname in entities:
  75. pvalue = entities.get(pname)
  76. parse_currency(pvalue)
  77. def add_q(i):
  78. return "Q" + str(i)
  79. def fetch_data_batch(wikidata_ids):
  80. while len(wikidata_ids) > 0:
  81. if len(wikidata_ids) > 50:
  82. fetch_data(wikidata_ids[0:49])
  83. wikidata_ids = wikidata_ids[50:]
  84. else:
  85. fetch_data(wikidata_ids)
  86. wikidata_ids = []
  87. def wdq_query(query):
  88. url = url_wmflabs_template + query
  89. htmlresponse = get(url)
  90. jsonresponse = json.loads(htmlresponse.content)
  91. qlist = map(add_q, jsonresponse.get('items', {}))
  92. error = jsonresponse.get('status', {}).get('error', None)
  93. if error is not None and error != 'OK':
  94. print "error for query '" + query + "' :" + error
  95. fetch_data_batch(qlist)
  96. def wd_query(query, offset=0):
  97. qlist = []
  98. url = url_wikidata_search_template.format(query=urlencode({'srsearch': query, 'srlimit': 50, 'sroffset': offset}))
  99. htmlresponse = get(url)
  100. jsonresponse = json.loads(htmlresponse.content)
  101. for r in jsonresponse.get('query', {}).get('search', {}):
  102. qlist.append(r.get('title', ''))
  103. fetch_data_batch(qlist)
  104. # fetch #
  105. for q in wmflabs_queries:
  106. wdq_query(q)
  107. # static
  108. add_currency_name(u"euro", 'EUR')
  109. add_currency_name(u"euros", 'EUR')
  110. add_currency_name(u"dollar", 'USD')
  111. add_currency_name(u"dollars", 'USD')
  112. add_currency_name(u"peso", 'MXN')
  113. add_currency_name(u"pesos", 'MXN')
  114. # write
  115. f = open("currencies.json", "wb")
  116. json.dump(db, f, indent=4, encoding="utf-8")
  117. f.close()