如何在python中将数字单词转换为数字 [英] How to convert numeric words into numeric in python

查看:85
本文介绍了如何在python中将数字单词转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把用文字表示的数字转换成数字.

I want to convert numeric which represented in words into numbers.

例如,三万四千四五十转化为对应的数值34450.还有一些模糊的转换,比如请支付三万四千四五十美元",然后输出为34450.

for example, thirty four thousand four fifty into its corresponding numerical value 34450. Also have some fuzzy conversions like "Please pay thirty-four thousand four fifty dollars" then the output to be 34450.

推荐答案

对于数字到单词,尝试num2words"包:https://pypi.python.org/pypi/num2words

For numbers to words, try "num2words" package: https://pypi.python.org/pypi/num2words

对于要num的单词,我从此处的代码中稍微调整了代码:有没有办法将数字转换为整数?

For words to num, I tweaked the code slightly from the code here: 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

->五十亿二十二万二十二三点二八

-> five billion two hundred and twenty two thousand two hundred and twenty three point two eight

-> 5000222223.28

-> 5000222223.28

这篇关于如何在python中将数字单词转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆