currency_convert.py 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import json
  2. import re
  3. import os
  4. import sys
  5. import unicodedata
  6. from datetime import datetime
  7. if sys.version_info[0] == 3:
  8. unicode = str
  9. categories = []
  10. url = 'https://finance.google.com/finance/converter?a=1&from={0}&to={1}'
  11. weight = 100
  12. parser_re = re.compile(b'.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I)
  13. db = 1
  14. def normalize_name(name):
  15. name = name.decode('utf-8').lower().replace('-', ' ').rstrip('s')
  16. name = re.sub(' +', ' ', name)
  17. return unicodedata.normalize('NFKD', name).lower()
  18. def name_to_iso4217(name):
  19. global db
  20. name = normalize_name(name)
  21. currencies = db['names'].get(name, [name])
  22. return currencies[0]
  23. def iso4217_to_name(iso4217, language):
  24. global db
  25. return db['iso4217'].get(iso4217, {}).get(language, iso4217)
  26. def request(query, params):
  27. m = parser_re.match(query)
  28. if not m:
  29. # wrong query
  30. return params
  31. amount, from_currency, to_currency = m.groups()
  32. amount = float(amount)
  33. from_currency = name_to_iso4217(from_currency.strip())
  34. to_currency = name_to_iso4217(to_currency.strip())
  35. q = (from_currency + to_currency).upper()
  36. params['url'] = url.format(from_currency, to_currency)
  37. params['amount'] = amount
  38. params['from'] = from_currency
  39. params['to'] = to_currency
  40. params['from_name'] = iso4217_to_name(from_currency, 'en')
  41. params['to_name'] = iso4217_to_name(to_currency, 'en')
  42. return params
  43. def response(resp):
  44. results = []
  45. pat = '<span class=bld>(.+) {0}</span>'.format(
  46. resp.search_params['to'].upper())
  47. try:
  48. conversion_rate = re.findall(pat, resp.text)[0]
  49. conversion_rate = float(conversion_rate)
  50. except:
  51. return results
  52. answer = '{0} {1} = {2} {3}, 1 {1} ({5}) = {4} {3} ({6})'.format(
  53. resp.search_params['amount'],
  54. resp.search_params['from'],
  55. resp.search_params['amount'] * conversion_rate,
  56. resp.search_params['to'],
  57. conversion_rate,
  58. resp.search_params['from_name'],
  59. resp.search_params['to_name'],
  60. )
  61. url = 'https://finance.google.com/finance?q={0}{1}'.format(
  62. resp.search_params['from'].upper(), resp.search_params['to'])
  63. results.append({'answer': answer, 'url': url})
  64. return results
  65. def load():
  66. global db
  67. current_dir = os.path.dirname(os.path.realpath(__file__))
  68. json_data = open(current_dir + "/../data/currencies.json").read()
  69. db = json.loads(json_data)
  70. load()