numerics.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #
  2. # numerics.py
  3. #
  4. # Examples of parsing real and integers using various grouping and
  5. # decimal point characters, varying by locale.
  6. #
  7. # Copyright 2016, Paul McGuire
  8. #
  9. # Format samples from https://docs.oracle.com/cd/E19455-01/806-0169/overview-9/index.html
  10. #
  11. tests = """\
  12. # Canadian (English and French)
  13. 4 294 967 295,000
  14. # Danish
  15. 4 294 967 295,000
  16. # Finnish
  17. 4 294 967 295,000
  18. # French
  19. 4 294 967 295,000
  20. # German
  21. 4 294 967 295,000
  22. # Italian
  23. 4.294.967.295,000
  24. # Norwegian
  25. 4.294.967.295,000
  26. # Spanish
  27. 4.294.967.295,000
  28. # Swedish
  29. 4 294 967 295,000
  30. # GB-English
  31. 4,294,967,295.000
  32. # US-English
  33. 4,294,967,295.000
  34. # Thai
  35. 4,294,967,295.000
  36. """
  37. from pyparsing import Regex
  38. comma_decimal = Regex(r'\d{1,2}(([ .])\d\d\d(\2\d\d\d)*)?,\d*')
  39. comma_decimal.setParseAction(lambda t: float(t[0].replace(' ','').replace('.','').replace(',','.')))
  40. dot_decimal = Regex(r'\d{1,2}(([ ,])\d\d\d(\2\d\d\d)*)?\.\d*')
  41. dot_decimal.setParseAction(lambda t: float(t[0].replace(' ','').replace(',','')))
  42. decimal = comma_decimal ^ dot_decimal
  43. decimal.runTests(tests, parseAll=True)
  44. grouped_integer = Regex(r'\d{1,2}(([ .,])\d\d\d(\2\d\d\d)*)?')
  45. grouped_integer.setParseAction(lambda t: int(t[0].replace(' ','').replace(',','').replace('.','')))
  46. grouped_integer.runTests(tests, parseAll=False)