jaraco / inflect

Correctly generate plurals, ordinals, indefinite articles; convert numbers to words
https://pypi.org/project/inflect
MIT License
957 stars 107 forks source link

How to force stop some groups in the string #198

Open ayrtondenner opened 1 year ago

ayrtondenner commented 1 year ago

Let's say that I have the number "41721", and I want my result in groups of two, BUT I want to group the first and last two digits of the number. In that case, my desired result is: "forty-one, seven, twenty-one".

Is there any way to force that? I saw an example in documentation using underscore, but couldn't find more explanation to that. So maybe:

import inflect
p = inflect.engine()
p.number_to_words("41_7_21", group=2)
p.number_to_words("41-7-21", group=2)
p.number_to_words("41 7 21", group=2)
...
jaraco commented 4 months ago

For the record, what that currently outputs is:

>>> p.number_to_words("41_7_21", group=2)
'forty-one, seventy-two, one'
>>> p.number_to_words("41-7-21", group=2)
'forty-one, seventy-two, one'
>>> p.number_to_words("41 7 21", group=2)
'forty-one, seventy-two, one'

I did discover I can get close to what you're seeking using a decimal:

>>> p.number_to_words("41.7.21", group=2)
'forty-one, point, seven, point, twenty-one'

And of course, you could repair the output:

>>> p.number_to_words("41.7.21", group=2).replace('point, ', '')
'forty-one, seven, twenty-one'

To be sure, that feels brittle.

Given the current implementation is already 150 lines, there's not a good abstraction for honoring stop groups.

Since you already have to go to the trouble of splitting them, why not use ', '.join(map(p.number_to_words, (41, 7, 21)))?