2016-02-20 126 views
2

我編寫了下面的代碼,它假設將所有數字從1轉換爲9999到單詞,但我的數字超出範圍111等請幫助。謝謝。將Python整數轉換爲單詞

global n2W 
n2W = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',\ 
     6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', \ 
     11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', \ 
     15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',\ 
     19: 'nineteen',20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 60:'sixty',\ 
     70: 'seventy', 80:'eighty', 90:'ninety',100:'one hundred', 200:'two hundred',\ 
     300:'three hundred', 400:'four hundred',500:'five hundred', 600:'six hundred',\ 
     700:'seven hundred',800:'eight hundred', 900:'nine hundred',\ 
     1000:'one thousand', 2000:'two thousand', 3000:'three thousand',\ 
     5000:'five thousand', 6000:'six thousand', 7000:'seven thousand',\ 
     8000:'eight thousand', 9000:'nine thousand',10000:'ten thousand'} 


def num2Word(n): 
    try: 
     print (n2W[n]) 
    except KeyError: 

     try: 
      print (n2W[n-n%10] , n2W[n%10].lower()) 
     except KeyError: 
      print ("Number out of range") 

n = eval(input("Please enter a number between 1 and 9999 inclusive: ")) 
num2Word(n) 
+1

http://stackoverflow.com/questions/19504350/h可能的重複將數字轉換爲單詞到python – Forge

回答

0

你最好使用num2words庫,它可以安裝使用:

pip install num2words 

然後你可以這樣做:手動

import num2words 
num2words.num2words(42) # forty-two 
+3

這將有助於作爲評論,但OP在想爲什麼他的代碼不能正常工作。你的回答沒有告訴他。 – zondo

+0

由於這看起來非常像家庭作業問題,我懷疑OP的教授/老師會接受這樣的事情。無論OP是不是要求圖書館來解決他們的問題,他們都會尋求幫助來修復他們現有的代碼。 – IanAuld

+0

我同意,但我會在這裏爲任何未來的搜索者留下這個答案。 –

0

只需插入一個號碼,你可以可以看到爲什麼有錯誤

例如try n = 111

(n2W[n-n%10] , n2W[n%10].lower())

111%10=1,所以你必須:

n2W[110]n2W[1]

n2W[110]是你的關鍵的錯誤,它只是需要通過你的函數遞歸回來。

1

您只能嘗試 - 除了一次,這意味着這將適用於最多2位數。嘗試遞歸地做。如果你想要的話,我可以給你一個有效的答案。 而不是做n2W [n%10] .lower(),對num2Word使用遞歸調用。

0

看看這個解決方案,我們從左到右迭代數字位數,將value映射到每次迭代中的文本,然後放棄最重要的數字。

def num2Word(n): 
    try: 
     word = '' 
     c = 1000 
     while n: 
      value = (n//c)*c if n > c else None 
      n %= c 
      c /= 10 
      if value is not None: 
       word += '%s ' % n2W[value] 
    except KeyError: 
     print ("Number out of range") 
    return word 

n = eval(input("Please enter a number between 1 and 9999 inclusive: ")) 
print num2Word(n) 


例如,對於n = 1234,我們將有四次迭代與value等於:

value = 1000
value = 200
value = 30
value = 4

+0

@dprogram請考慮接受答案,如果它對你有幫助,點擊複選標記。 – Forge