」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Python 中使用 Inflect 將整數轉換為單字?

如何在 Python 中使用 Inflect 將整數轉換為單字?

發佈於2024-11-08
瀏覽:689

How to Convert Integers to Words in Python Using Inflect?

在Python 中將整數轉換為單字

在Python 中將數值轉換為對應的單字表示形式可能是一項令人費解的任務。本文探討了使用 inflect 套件的簡單解決方案。

困境:

困境:

該示例嘗試將歌曲“99 Bottles of Beer”打印在Wall”,用文字替換數值。然而,代碼目前顯示的是數字而不是它們的口語對應。下列步驟操作:

    安裝inflect:
  1. 安裝inflect:
$ pip install inflect
    $ pip install inflect
  1. 導入inflect:
import inflect
    進口inflect
  1. 創建一個inflect 引擎:
import inflect
    p = inflect.engine()
  1. 將數字轉換為單字:
import inflect

p.number_to_words(99)

ninety-nine

九十九

範例:

import inflect

p = inflect.engine()

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

導入變形 p = inflect.engine() 對於範圍 (99, 0, -1) 內的 i: print(p.number_to_words(i), "牆上的啤酒瓶,") print(p.number_to_words(i), "幾瓶啤酒。") print("拿下一份並傳給大家,") print(p.number_to_words(i - 1), "牆上的啤酒瓶。") print()

此程式碼現在將使用文字而不是數字來列印「99 Bottles of Beer on the Wall」的歌詞。 How to Convert Integers to Words in Python Using Inflect?

版本聲明 本文轉載於:1729318396如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3