numbers.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import re
  2. import inflect
  3. _inflect = inflect.engine()
  4. _comma_number_re = re.compile(r"([0-9][0-9\,]+[0-9])")
  5. _decimal_number_re = re.compile(r"([0-9]+\.[0-9]+)")
  6. _pounds_re = re.compile(r"£([0-9\,]*[0-9]+)")
  7. _dollars_re = re.compile(r"\$([0-9\.\,]*[0-9]+)")
  8. _ordinal_re = re.compile(r"[0-9]+(st|nd|rd|th)")
  9. _number_re = re.compile(r"[0-9]+")
  10. def _remove_commas(m):
  11. return m.group(1).replace(",", "")
  12. def _expand_decimal_point(m):
  13. return m.group(1).replace(".", " point ")
  14. def _expand_dollars(m):
  15. match = m.group(1)
  16. parts = match.split(".")
  17. if len(parts) > 2:
  18. return match + " dollars" # Unexpected format
  19. dollars = int(parts[0]) if parts[0] else 0
  20. cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0
  21. if dollars and cents:
  22. dollar_unit = "dollar" if dollars == 1 else "dollars"
  23. cent_unit = "cent" if cents == 1 else "cents"
  24. return "%s %s, %s %s" % (dollars, dollar_unit, cents, cent_unit)
  25. elif dollars:
  26. dollar_unit = "dollar" if dollars == 1 else "dollars"
  27. return "%s %s" % (dollars, dollar_unit)
  28. elif cents:
  29. cent_unit = "cent" if cents == 1 else "cents"
  30. return "%s %s" % (cents, cent_unit)
  31. else:
  32. return "zero dollars"
  33. def _expand_ordinal(m):
  34. return _inflect.number_to_words(m.group(0))
  35. def _expand_number(m):
  36. num = int(m.group(0))
  37. if num > 1000 and num < 3000:
  38. if num == 2000:
  39. return "two thousand"
  40. elif num > 2000 and num < 2010:
  41. return "two thousand " + _inflect.number_to_words(num % 100)
  42. elif num % 100 == 0:
  43. return _inflect.number_to_words(num // 100) + " hundred"
  44. else:
  45. return _inflect.number_to_words(num, andword="", zero="oh", group=2).replace(", ", " ")
  46. else:
  47. return _inflect.number_to_words(num, andword="")
  48. def normalize_numbers(text):
  49. text = re.sub(_comma_number_re, _remove_commas, text)
  50. text = re.sub(_pounds_re, r"\1 pounds", text)
  51. text = re.sub(_dollars_re, _expand_dollars, text)
  52. text = re.sub(_decimal_number_re, _expand_decimal_point, text)
  53. text = re.sub(_ordinal_re, _expand_ordinal, text)
  54. text = re.sub(_number_re, _expand_number, text)
  55. return text