2016-12-28 56 views
0

我想將單詞中表示的數字轉換爲數字。如何將數字轉換爲python中的數字

例如, thirty four thousand four fifty變成其相應的數值34450。 也有一些模糊轉換如"Please pay thirty-four thousand four fifty dollars"然後輸出爲34450

+0

這是一個愚蠢的實現:http://pastebin.com/WwFCjYtt =) – alvas

回答

2

對於號碼的話,試試 「num2words」 套餐: https://pypi.python.org/pypi/num2words

,說不出話NUM,我調整了代碼稍微從這裏代碼: Is there a way to convert number words to Integers?

from num2words import num2words 

def text2int(textnum, numwords={}): 
    if not numwords: 
     units = [ 
     "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", 
     "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", 
     "sixteen", "seventeen", "eighteen", "nineteen", 
     ] 

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

     scales = ["hundred", "thousand", "million", "billion", "trillion"] 

     numwords["and"] = (1, 0) 
     for idx, word in enumerate(units): numwords[word] = (1, idx) 
     for idx, word in enumerate(tens):  numwords[word] = (1, idx * 10) 
     for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0) 

    current = result = 0 
    for word in textnum.split(): 
     if word not in numwords: 
      raise Exception("Illegal word: " + word) 

     scale, increment = numwords[word] 
     current = current * scale + increment 
     if scale > 100: 
      result += current 
      current = 0 

    return result + current 

#### My update to incorporate decimals 
num = 5000222223.28 
fullText = num2words(num).replace('-',' ').replace(',',' ') 
print fullText 

decimalSplit = fullText.split('point ') 

if len(decimalSplit) > 1: 
    decimalSplit2 = decimalSplit[1].split(' ') 
    decPart = sum([float(text2int(decimalSplit2[x]))/(10)**(x+1) for x in range(len(decimalSplit2))]) 
else: 
    decPart = 0 

intPart = float(text2int(decimalSplit[0])) 

Value = intPart + decPart 

print Value 

- >五類十億2一百二十二二百二十三點二八八

- > 5000222223.28

+0

我要求字數到數字,而不是數字到字 –

+0

我已經更新了答案 – Oxymoron88

+0

我不認爲它將能夠轉換小數點@ Oxymoron88 –

相關問題