0

ライブラリ関数を使用せずに、Python で任意の数の単語を出力するにはどうすればよいですか? ライブラリ関数を使用していたという回答がいくつかありますが、コアコードが必要です。

Like:
    12345 = "twelve thousand three hundred and forty five"
    97835200 ="Nine core seventy eight lakh thirty five thousand two hundred"
    230100 = "Two lakh thirty thousand one hundred"
4

3 に答える 3

3

あなたはPythonで利用可能なサードパーティのライブラリnum2wordを使用しています

num2word.to_card(1e25)
'ten septillion, one billion, seventy-three million, seven hundred and forty-one


this will avoid your long code and you can directly use it.
于 2013-04-25T14:32:52.970 に答える
1

以下は、数字を単語に変換できる関数です。番号には標準の英語名が使用されますが、必要に応じて特別な名前に変更できます。この関数は、最大 10^60 の数値を処理できます。関数を呼び出して使用します: int2word(n) ここで、n は数値です。

def int2word(n):
"""
convert an integer number n into a string of english words
"""
# break the number into groups of 3 digits using slicing
# each group representing hundred, thousand, million, billion, ...
n3 = []
r1 = ""
# create numeric string
ns = str(n)
for k in range(3, 33, 3):
    r = ns[-k:]
    q = len(ns) - k
    # break if end of ns has been reached
    if q < -2:
        break
    else:
        if  q >= 0:
            n3.append(int(r[:3]))
        elif q >= -1:
            n3.append(int(r[:2]))
        elif q >= -2:
            n3.append(int(r[:1]))
    r1 = r

#print n3  # test

# break each group of 3 digits into
# ones, tens/twenties, hundreds
# and form a string
nw = ""
for i, x in enumerate(n3):
    b1 = x % 10
    b2 = (x % 100)//10
    b3 = (x % 1000)//100
    #print b1, b2, b3  # test
    if x == 0:
        continue  # skip
    else:
        t = thousands[i]
    if b2 == 0:
        nw = ones[b1] + t + nw
    elif b2 == 1:
        nw = tens[b1] + t + nw
    elif b2 > 1:
        nw = twenties[b2] + ones[b1] + t + nw
    if b3 > 0:
        nw = ones[b3] + "hundred " + nw
return nw

'''Global'''

ones = ["", "one ","two ","three ","four ", "five ",
"six ","seven ","eight ","nine "]

tens = ["ten ","eleven ","twelve ","thirteen ", "fourteen ",
"fifteen ","sixteen ","seventeen ","eighteen ","nineteen "]

twenties = ["","","twenty ","thirty ","forty ",
"fifty ","sixty ","seventy ","eighty ","ninety "]

thousands = ["","thousand ","million ", "billion ", "trillion ",
"quadrillion ", "quintillion ", "sextillion ", "septillion ","octillion ",
"nonillion ", "decillion ", "undecillion ", "duodecillion ", "tredecillion ",
"quattuordecillion ", "sexdecillion ", "septendecillion ", "octodecillion ",
"novemdecillion ", "vigintillion "]
于 2013-04-25T14:32:04.307 に答える