Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแปลงตัวเลขเป็นคำอ่านด้วย Python

Constructor ของคลาส string ใน Python คือ str ใช้แปลงตัวเลขเป็นสตริงได้ เช่น

i = 10050
str_i = str(i)
print(type(str_i))

ผลลัพธ์:

<class 'str'>

แต่ถ้าต้องการแปลงเป็นคำอ่าน เช่น 99 เป็น ninety-nine ต้องใช้แพ็กเกจภายนอกหรือสร้างเอง โมดูล pynum2word ทำได้ดี ติดตั้งด้วย

$ pip install pynum2word

ใช้ดังนี้

>>> import num2word
>>> num2word.to_card(16)
'sixteen'
>>> num2word.to_card(23)
'twenty-three'
>>> num2word.to_card(1223)
'one thousand, two hundred and twenty-three'