解释python代码:complete_number [word] =(10 **(index * 3或2),0)

时间:2018-09-06 22:11:23

标签: python-3.x

我正在尝试了解Is there a way to convert number words to Integers?中的代码。我无法理解以下声明:

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

下面是代码:

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

print text2int("seven billion one hundred million thirty one thousand three hundred thirty seven")
#7100031337

1 个答案:

答案 0 :(得分:0)

据我了解,它可以根据它在该数组中的位置找到每个标度字(百万,十亿,万亿)加10 ^(3x),我用x表示。