word to digit module

M.E.Farmer mefjr75 at hotmail.com
Wed Dec 22 22:18:47 CET 2004


Cool script just one little thing,
toNumber('One thousand') bites the dust.
Guess you should add another test, and s.lower() ;)

Stephen Thorne wrote:
{code snip}
> def toNumber(s):
+     s = s.lower()
>     items = s.replace(',', '').split()
>     numbers = [translation.get(item.strip(), -1) for item in items if
> item.strip()]
>     if -1 in numbers:
>         raise ValueError("Invalid string '%s'" % (s,))
>
>     if 1000 in numbers:
>         idx = numbers.index(1000)
>         hundreds = numbers[:idx]
>         numbers = numbers[idx+1:] + [1000*x for x in hundreds]
>
>     if 100 in numbers:
>         idx = numbers.index(100)
>         hundreds = numbers[:idx]
>         numbers = numbers[idx+1:] + [100*x for x in hundreds]
> 
>     return sum(numbers)
> 
> Stephen Thorne

M.E.Farmer




More information about the Python-list mailing list