添加单词数字

时间:2015-10-29 23:04:29

标签: python

我试图通过使用整数形式和数字的文本形式来添加数字。我已经将整数方面缩小了,但在尝试打印文本版本时遇到错误。

#!/usr/bin/python

question = raw_input("Do math with numbers or text? (n/t) ")
if question == "n":


    x = int(input("Enter a digit: "))
    y = raw_input("Enter a sign: ")
    z = int(input("Enter another digit: "))
    sum = x+z
    diff = x-z
    mult = x*z
    divi = x/z

    if y == "+":
            print(sum)
    if y == "-":
            print(diff)
    if y == "*":
            print(mult)
    if y == "/":
            print(divi)

if question == "t":

    def toNum(words, num={}):
      if not num:
            teens = ["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"]
            hund = ["hundred", "thousand"]

       num["and"] = (1, 0)
            for place, word in enumerate(teens): num[word] = (1, place)
            for place, word in enumerate(tens): num[word] = (1, place * 10)
            for place, word in enumerate(hund): num[word] = (10 ** (place * 3 or 2), 0)

            input = result = 0
            for word in words.split():
                    if word not in num:
                            raise Exception(word)

                    hund, increment = num[word]
                    input = input * hund + increment
                    if hund > 100:
                            result += input
                            input = 0

            return result + input

    x = toNum(raw_input("Enter a number: "))
    y = toNum(raw_input("Enter a sign: "))
    z = toNum(raw_input("Enter another number: "))

    sum = x + z
    diff = x - z
    mult = x * z
    divi = x / z

    if y == "+":
            print(sum)
    if y == "-":
            print(diff)
    if y == "*":
            print(mult)
    if y == "/":
            print(divi)

运行后,键入" t",并输入我的数字和符号,它表示" TypeError:不支持的操作数类型+:' int'和' NoneType' -bash:意外令牌附近的语法错误'(`

不确定如何使用单词数字进行数学计算,并将它们全部用完。非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

我在我的副本中修复了缩进并重现了问题。您尚未正确测试您的" toNum"常规;它返回进行操作(不是问题,因为你不使用它)和第二个数字(我做了#34;一个" +"七& #34;。)

我可以看到,基本问题是 toNum 在某些情况下不会返回任何 - 这会带回无< / strong>价值。

我建议您添加一些打印语句来跟踪问题...并逐步进展。