numbers.py 2.3 KB

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