Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

How do I tell Python to convert integers into words

I'm trying to tell Python to convert integers into words.

Example: (using the song 99 bottles of beer on the wall)

I used this code to write the program:

for i in range(99,0,-1):
    print i, "Bottles of beer on the wall,"
    print i, "bottles of beer."
    print "Take one down and pass it around,"
    print i-1, "bottles of beer on the wall."
    print

But I cannot figure out how to write the program so that the words (i.e. Ninety nine, Ninety eight, etc.) will be displayed instead of the numbers.

I have been wracking my head in the python book I have, I understand that maybe I just do not understand for/if/elif/else loops yet but I'm just spinning my wheels.

Could anyone provide any insight? I'm not looking for a direct answer, although that might help me see my problem, just anything to point me in the right direction would be great.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The inflect package can do this.

https://pypi.python.org/pypi/inflect

$ pip install inflect

and then:

>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(99)
ninety-nine

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...