Returns the given numeric string as a float or an int. If no number can be parsed from the string, returns 0. For example: number("five point two million") => 5200000 number("seventy-five point two") => 75.2 number("three thousand and one") => 3001
(s)
| 93 | #--- STRING TO NUMBER ------------------------------------------------------------------------------ |
| 94 | |
| 95 | def number(s): |
| 96 | """ Returns the given numeric string as a float or an int. |
| 97 | If no number can be parsed from the string, returns 0. |
| 98 | For example: |
| 99 | number("five point two million") => 5200000 |
| 100 | number("seventy-five point two") => 75.2 |
| 101 | number("three thousand and one") => 3001 |
| 102 | """ |
| 103 | s = s.strip() |
| 104 | s = s.lower() |
| 105 | # Negative number. |
| 106 | if s.startswith(MINUS): |
| 107 | return -number(s.replace(MINUS, "", 1)) |
| 108 | # Strip commas and dashes ("seventy-five"). |
| 109 | # Split into integral and fractional part. |
| 110 | s = s.replace("&", " %s " % CONJUNCTION) |
| 111 | s = s.replace(THOUSANDS, "") |
| 112 | s = s.replace("-", " ") |
| 113 | s = s.split(RADIX) |
| 114 | # Process fractional part. |
| 115 | # Extract all the leading zeros. |
| 116 | if len(s) > 1: |
| 117 | f = " ".join(s[1:]) # zero point zero twelve => zero twelve |
| 118 | f, z = zshift(f) # zero twelve => (1, "twelve") |
| 119 | f = float(number(f)) # "twelve" => 12.0 |
| 120 | f /= 10**(len(str(int(f)))+z) # 10**(len("12")+1) = 1000; 12.0 / 1000 => 0.012 |
| 121 | else: |
| 122 | f = 0 |
| 123 | i = n = 0 |
| 124 | s = s[0].split() |
| 125 | for j, x in enumerate(s): |
| 126 | if x in NUMERALS: |
| 127 | # Map words from the dictionary of numerals: "eleven" => 11. |
| 128 | i += NUMERALS[x] |
| 129 | elif x in NUMERALS_VERBOSE: |
| 130 | # Map words from alternate numerals: "two dozen" => 2 * 12 |
| 131 | i = i * NUMERALS_VERBOSE[x][0] + NUMERALS_VERBOSE[x][1] |
| 132 | elif x in O: |
| 133 | # Map thousands from the dictionary of orders. |
| 134 | # When a thousand is encountered, the subtotal is shifted to the total |
| 135 | # and we start a new subtotal. An exception to this is when we |
| 136 | # encouter two following thousands (e.g. two million vigintillion is one subtotal). |
| 137 | i *= O[x] |
| 138 | if j < len(s)-1 and s[j+1] in O: |
| 139 | continue |
| 140 | if O[x] > 100: |
| 141 | n += i |
| 142 | i = 0 |
| 143 | elif x == CONJUNCTION: |
| 144 | pass |
| 145 | else: |
| 146 | # Words that are not in any dicionary may be numbers (e.g. "2.5" => 2.5). |
| 147 | try: i += "." in x and float(x) or int(x) |
| 148 | except: |
| 149 | pass |
| 150 | return n + i + f |
| 151 | |
| 152 | #print number("five point two septillion") |