On Wed, 22 Dec 2004 11:41:26 -0800, Scott David Daniels
<[EMAIL PROTECTED]> wrote:
> John Machin wrote:
> > Stephen Thorne wrote:
> > .def toNumber2(s):
> > . items = s.replace(',', '').split()
> > . numbers = [translation.get(item.strip(), -1) for item in items if
> > item.strip()]
> > . stack = [0]
> > . for num in numbers:
> > . if num == -1:
> > . raise ValueError("Invalid string '%s'" % (s,))
> > . if num >= 100:
> > . stack[-1] *= num
> > . if num >= 1000:
> > . stack.append(0)
> > . else:
> > . stack[-1] += num
> > . return sum(stack)
> >
>
> Can I play too?
> Let's replace the top with some little bit of error handling:
>
> def toNumber3(text):
> s = text.replace(',', '').replace('-', '')# for twenty-three
> items = s.split()
> try:
> numbers = [translation[item] for item in items]
> except KeyError, e:
> raise ValueError, "Invalid element %r in string %r" % (
> e.args[0], text)
> stack = [0]
> for num in numbers:
> if num >= 100:
> stack[-1] *= num
> if num >= 1000:
> stack.append(0)
> else:
> stack[-1] += num
> return sum(stack)
Thankyou for you feedback, both of you.
http://thorne.id.au/users/stephen/scripts/eng2num.py contains your suggestions.
Stephen.
--
http://mail.python.org/mailman/listinfo/python-list