forked from harvardnlp/data2text
-
Notifications
You must be signed in to change notification settings - Fork 14
/
text2num.py
420 lines (338 loc) · 11.7 KB
/
text2num.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# copied from: https://github.com/exogen/text2num/blob/289745aebaf91e312fa8f8d86e04c17d7a3771af/text2num.py
# This library is a simple implementation of a function to convert textual
# numbers written in English into their integer representations.
#
# This code is open source according to the MIT License as follows.
#
# Copyright (c) 2008 Greg Hewgill
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Convert textual numbers written in English into their integer representations.
>>> text2num("zero")
0
>>> text2num("one")
1
>>> text2num("twelve")
12
>>> text2num("nineteen")
19
>>> text2num("twenty nine")
29
>>> text2num("seventy two")
72
>>> text2num("three hundred")
300
>>> text2num("twelve hundred")
1200
>>> text2num("nineteen hundred eighty four")
1984
Hundreds may be implied without a 'hundreds' token if no other magnitudes
are present:
>>> text2num("one thirty")
130
>>> text2num("six sixty two")
662
>>> text2num("ten twelve")
1012
>>> text2num("nineteen ten")
1910
>>> text2num("nineteen eighty four")
1984
>>> text2num("twenty ten")
2010
>>> text2num("twenty twenty")
2020
>>> text2num("twenty twenty one")
2021
>>> text2num("fifty sixty three")
5063
>>> text2num("one thirty thousand")
Traceback (most recent call last):
...
NumberException: 'thousand' may not proceed implied hundred 'one thirty'
>>> text2num("nineteen eighty thousand")
Traceback (most recent call last):
...
NumberException: 'thousand' may not proceed implied hundred
'nineteen eighty'
>>> text2num("twelve thousand three hundred four")
12304
>>> text2num("six million")
6000000
>>> text2num("six million four hundred thousand five")
6400005
>>> text2num("one hundred twenty three billion four hundred fifty six "
... "million seven hundred eighty nine thousand twelve")
123456789012
>>> text2num("four decillion")
4000000000000000000000000000000000
>>> text2num("one hundred thousand")
100000
>>> text2num("one hundred two thousand")
102000
Magnitudes must magnify a number and appear in descending order (except
for hundreds, since it can magnify other magnitudes).
>>> text2num("thousand")
Traceback (most recent call last):
...
NumberException: magnitude 'thousand' must be preceded by a number
>>> text2num("hundred one")
Traceback (most recent call last):
...
NumberException: magnitude 'hundred' must be preceded by a number
>>> text2num("one thousand thousand")
Traceback (most recent call last):
...
NumberException: magnitude 'thousand' must be preceded by a number
>>> text2num("one thousand two thousand")
Traceback (most recent call last):
...
NumberException: magnitude 'thousand' appeared out of order following
'one thousand two'
>>> text2num("one hundred two hundred")
Traceback (most recent call last):
...
NumberException: magnitude 'hundred' appeared out of order following
'one hundred two'
>>> text2num("one thousand two million")
Traceback (most recent call last):
...
NumberException: magnitude 'million' appeared out of order following
'one thousand two'
>>> text2num("nine one")
Traceback (most recent call last):
...
NumberException: 'one' may not proceed 'nine'
>>> text2num("ten two")
Traceback (most recent call last):
...
NumberException: 'two' may not proceed 'ten'
>>> text2num("nineteen nine")
Traceback (most recent call last):
...
NumberException: 'nine' may not proceed 'nineteen'
>>> text2num("sixty five hundred")
6500
>>> text2num("sixty hundred")
6000
>>> text2num("ten hundred twelve")
1012
>>> text2num("twenty twenty ten")
Traceback (most recent call last):
...
NumberException: 'ten' may not proceed 'twenty' following 'twenty'
>>> text2num("three thousand nineteen eighty four")
Traceback (most recent call last):
...
NumberException: 'eighty' may not proceed 'nineteen' following
'three thousand'
>>> text2num("three million nineteen eighty four")
Traceback (most recent call last):
...
NumberException: 'eighty' may not proceed 'nineteen' following
'three million'
>>> text2num("one million eighty eighty")
Traceback (most recent call last):
...
NumberException: 'eighty' may not proceed 'eighty' following 'one million'
>>> text2num("one million eighty one")
1000081
>>> text2num("zero zero")
Traceback (most recent call last):
...
NumberException: 'zero' may not appear with other numbers
>>> text2num("one zero")
Traceback (most recent call last):
...
NumberException: 'zero' may not appear with other numbers
>>> text2num("zero thousand")
Traceback (most recent call last):
...
NumberException: 'zero' may not appear with other numbers
>>> text2num("foo thousand")
Traceback (most recent call last):
...
NumberException: unknown number: 'foo'
Strings may optionally include the word 'and', but only in positions
that make sense:
>>> text2num("one thousand and two")
1002
>>> text2num("ten hundred and twelve")
1012
>>> text2num("nineteen hundred and eighty eight")
1988
>>> text2num("one hundred and ten thousand and one")
110001
>>> text2num("forty and two")
Traceback (most recent call last):
...
NumberException: 'and' must be preceeded by a magnitude but got 'forty'
>>> text2num("one and")
Traceback (most recent call last):
...
NumberException: 'and' must be preceeded by a magnitude but got 'one'
>>> text2num("and one")
Traceback (most recent call last):
...
NumberException: 'and' must be preceeded by a magnitude
>>> text2num("one hundred and")
Traceback (most recent call last):
...
NumberException: 'and' must be followed by a number
>>> text2num("nineteen and eighty eight")
Traceback (most recent call last):
...
NumberException: 'and' must be preceeded by a magnitude but got 'nineteen'
"""
import re
SMALL = {
'zero': 0,
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9,
'ten': 10,
'eleven': 11,
'twelve': 12,
'thirteen': 13,
'fourteen': 14,
'fifteen': 15,
'sixteen': 16,
'seventeen': 17,
'eighteen': 18,
'nineteen': 19,
'twenty': 20,
'thirty': 30,
'forty': 40,
'fifty': 50,
'sixty': 60,
'seventy': 70,
'eighty': 80,
'ninety': 90
}
MAGNITUDE = {
'hundred': 100,
'thousand': 1000,
'million': 1000000,
'billion': 1000000000,
'trillion': 1000000000000,
'quadrillion': 1000000000000000,
'quintillion': 1000000000000000000,
'sextillion': 1000000000000000000000,
'septillion': 1000000000000000000000000,
'octillion': 1000000000000000000000000000,
'nonillion': 1000000000000000000000000000000,
'decillion': 1000000000000000000000000000000000,
}
class NumberException(Exception):
"""
Number parsing error.
"""
pass
def text2num(s):
"""
Convert the English number phrase `s` into the integer it describes.
"""
# pylint: disable=invalid-name,too-many-branches,undefined-loop-variable
words = re.split(r'[\s,-]+', s)
if not words:
raise NumberException("no numbers in string: {!r}".format(s))
n = 0
g = 0
implied_hundred = False
for i, word in enumerate(words):
tens = g % 100
if word == "and":
if i and tens == 0:
# If this isn't the first word, and `g` was multiplied by 100
# or reset to 0, then we're in a spot where 'and' is allowed.
continue
else:
fmt = (word, " but got {!r}".format(words[i - 1]) if i else "")
raise NumberException("{!r} must be preceeded by a magnitude"
"{}".format(*fmt))
x = SMALL.get(word, None)
if x is not None:
if x == 0 and len(words) > 1:
raise NumberException("{!r} may not appear with other "
"numbers".format(word))
if tens != 0:
# Check whether the two small numbers can be treated as if an
# implied 'hundred' is present, as in 'nineteen eighty four'.
if x >= 10:
# Only allow implied hundreds if no other magnitude is
# already present.
if n == 0:
n += g * 100
g = 0
implied_hundred = True
else:
fmt = (word, words[i - 1], " ".join(words[:i - 1]))
raise NumberException("{!r} may not proceed {!r} "
"following {!r}".format(*fmt))
# Treat sequences like 'nineteen one' as errors rather than
# interpret them as 'nineteen hundred one', 'nineteen aught
# one', 'nineteen oh one', etc. But continue if we have 20 or
# greater in the accumulator to support 'twenty one', 'twenty
# two', etc.
elif tens < 20:
raise NumberException("{!r} may not proceed "
"{!r}".format(word, words[i - 1]))
g += x
else:
x = MAGNITUDE.get(word, None)
if x is None:
raise NumberException("unknown number: {!r}".format(word))
# We could check some of these branches in the conditional one
# level up, but would prefer the 'unknown number' exception take
# precedence since it's a bigger problem.
elif implied_hundred:
fmt = (word, " ".join(words[:i]))
raise NumberException("{!r} may not proceed implied hundred "
"{!r}".format(*fmt))
# Disallow standalone magnitudes and multiple magnitudes like
# 'one thousand million' where 'one billion' should be used
# instead.
elif g == 0:
raise NumberException("magnitude {!r} must be preceded by a "
"number".format(word))
# Check whether this magnitude was preceded by a lower one.
elif 0 < n <= x or g >= x:
fmt = (word, " ".join(words[:i]))
raise NumberException("magnitude {!r} appeared out of order "
"following {!r}".format(*fmt))
# Accumulate hundreds in `g`, not `n`, since hundreds can magnify
# other magnitudes.
elif x == 100:
g *= x
else:
n += g * x
g = 0
# We could check whether the last word is 'and' at the very beginning and
# fail early, but this way errors are raised in the order each word is
# seen, as if we're processing a stream.
if word == "and":
raise NumberException("{!r} must be followed by a number".format(word))
return n + g