forked from songzy12/text-normalization-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnormalizer.py
More file actions
422 lines (377 loc) · 12.3 KB
/
normalizer.py
File metadata and controls
422 lines (377 loc) · 12.3 KB
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
421
422
#encoding=utf8
########################################################
'''
READ MY COMMENT BELOW
'''
########################################################
import os
import operator
from num2words import num2words
import gc
import io
import json
import re
import string
import code
from io import open
from helper import *
INPUT_PATH = r'./input'
DATA_INPUT_PATH = r'./input/en_with_types'
SUBM_PATH = r'./output'
SUB = str.maketrans("₀₁₂₃₄₅₆₇₈₉", "0123456789")
SUP = str.maketrans("⁰¹²³⁴⁵⁶⁷⁸⁹", "0123456789")
OTH = str.maketrans("፬", "4")
#SUB = None
#SUP = None
#OTH = None
INCH_TMP = r'\d+""'
def inflect_transform(data):
data = re.sub(r'-|,|\band\b', ' ', data)
data = data.split(' ')
data = [x for x in data if x is not '']
return ' '.join(data)
def WEB_transform(data):
if '.' not in data:
return data
before = data
after = []
m = {u'.':'dot',
u'/':'slash',
u':':'colon',
u',':'comma',
u'-':'dash'}
for char in data:
if char in m:
after.append(m[char])
else:
after.append(char)
after = ' '.join(after)
#print('before:', before)
#print('after:', after)
return ' '.join(after)
def INCH_transform(data):
neo_data = data[:-2]
return ' '.join([inflect_transform(num2words(int(neo_data))), 'inches'])
def train():
print('Train start...')
file = "en_train.csv"
train = open(os.path.join(INPUT_PATH, "en_train.csv"), encoding='UTF8')
line = train.readline()
#res = dict()
res_class = dict()
total = 0
not_same = 0
while 1:
line = train.readline().strip()
if line == '':
break
total += 1
pos = line.find('","')
text = line[pos + 2:]
if text[:3] == '","':
continue
text = text[1:-1]
arr = text.split('","')
# arr[0], arr[1] are 'before', 'after' now
pos_class = line.find(',"')
text_class = line[pos_class+2:pos]
if arr[0] != arr[1]:
not_same += 1
#if arr[0] not in res:
# res[arr[0]] = dict()
# res[arr[0]][arr[1]] = 1
#else:
# if arr[1] in res[arr[0]]:
# res[arr[0]][arr[1]] += 1
# else:
# res[arr[0]][arr[1]] = 1
if ('.'.join([arr[0], text_class])) not in res_class:
res_class['.'.join([arr[0], text_class])] = dict()
res_class['.'.join([arr[0], text_class])][arr[1]] = 1
else:
if arr[1] in res_class['.'.join([arr[0], text_class])]:
res_class['.'.join([arr[0], text_class])][arr[1]] += 1
else:
res_class['.'.join([arr[0], text_class])][arr[1]] = 1
train.close()
print(file + ':\tTotal: {} Have diff value: {}'.format(total, not_same))
#files = os.listdir(DATA_INPUT_PATH)
#for file in files:
# train = open(os.path.join(DATA_INPUT_PATH, file), encoding='UTF8')
# while 1:
# line = train.readline().strip()
# if line == '':
# break
# total += 1
# pos = line.find('\t')
# text = line[pos + 1:]
# if text[:3] == '':
# continue
# arr = text.split('\t')
# if arr[0] == '<eos>':
# continue
# if arr[1] != '<self>':
# not_same += 1
#
# if arr[1] == '<self>' or arr[1] == 'sil':
# arr[1] = arr[0]
#
# if arr[0] not in res:
# res[arr[0]] = dict()
# res[arr[0]][arr[1]] = 1
# else:
# if arr[1] in res[arr[0]]:
# res[arr[0]][arr[1]] += 1
# else:
# res[arr[0]][arr[1]] = 1
# train.close()
# print(file + ':\tTotal: {} Have diff value: {}'.format(total, not_same))
# res is now all the ['before']['after'] pairs
gc.collect()
#return res
return res_class
def dump_res(res, path):
with io.open(path, 'w', encoding='utf8') as f:
f.write(json.dumps(res, ensure_ascii=False, indent=4))
def load_res(path):
with io.open(path) as f:
res = json.loads(f.read())
return res
#res = train()
res_path = './output/res.json'
res_class_path = './output/res_class.json'
#dump_res(res, path)
res_class = load_res(res_class_path)
res = load_res(res_path)
print('len(res): {}'.format(len(res)))
print('len(res_class): {}'.format(len(res_class)))
sdict = {}
sdict['km2'] = 'square kilometers'
sdict['km'] = 'kilometers'
sdict['kg'] = 'kilograms'
sdict['lb'] = 'pounds'
sdict['dr'] = 'doctor'
sdict['m²'] = 'square meters'
def test():
total = 0
changes = 0
m = {}
out = open(os.path.join(SUBM_PATH, 'baseline_ext_class_en.csv'), "w", encoding='UTF8')
out.write('"id","after"\n')
test = open(os.path.join(INPUT_PATH, "en_test_2.csv"), encoding='UTF8')
pred = open(os.path.join(SUBM_PATH, "pred_test_2.csv"), encoding='UTF8')
line = test.readline().strip()
line_pred = pred.readline().strip()
while 1:
line = test.readline().strip()
try:
line_pred = pred.readline().strip()
except:
code.interact(local=locals())
if line == '':
break
pos = line.find(',')
i1 = line[:pos]
line = line[pos + 1:]
pos = line.find(',')
i2 = line[:pos]
line = line[pos + 1:]
line = line[1:-1]
out.write('"' + i1 + '_' + i2 + '",')
pos = line_pred.rfind(',')
tag = line_pred[pos + 1:]
label = tag
before = line
if ".".join([line, tag]) in res_class:
srtd = sorted(res_class[".".join([line, tag])].items(), key=operator.itemgetter(1), reverse=True)
line = srtd[0][0]
line = re.sub(r'\b_letter\b', ' ', line)
for l in string.ascii_letters[:26]:
line = re.sub(l+'_letter', l, line)
line = ' '.join(filter(lambda x: x, line.split(' ')))
#if before != line:
# print('before:', before)
# print('after:', line)
out.write('"' + line + '"')
m[".".join([before, tag])] = line
changes += 1
elif line in res:
#if len(res[line]) > 1:
# m[line] = [total, res[line]]
if tag == 'ELECTRONIC' and '.' in line:
line = WEB_transform(line)
else:
# here return the first (value, cnt) with line as key
srtd = sorted(res[line].items(), key=operator.itemgetter(1), reverse=True)
line = srtd[0][0]
before = line
line = re.sub(r'\b_letter\b', ' ', line)
for l in string.ascii_letters[:26]:
line = re.sub(l+'_letter', l, line)
line = ' '.join(filter(lambda x: x, line.split(' ')))
#if before != line:
# print('before:', before)
# print('after:', line)
out.write('"' + line + '"')
changes += 1
elif label == 'ADDRESS':
try:
norm = address(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'CARDINAL'
elif label == 'CARDINAL':
try:
norm = cardinal(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'DATE'
elif label == 'DATE':
try:
norm = date(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'DECIMAL'
elif label == 'DECIMAL':
try:
norm = decimal(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'DIGIT',
elif label == 'DIGIT':
try:
norm = digit(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'ELECTRONIC',
elif label == 'ELECTRONIC':
try:
norm = electronic(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'FRACTION',
elif label == 'FRACTION':
try:
norm = fraction(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'LETTERS',
elif label == 'LETTERS':
try:
norm = letters(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'MEASURE',
elif label == 'MEASURE':
try:
norm = measure(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'MONEY',
elif label == 'MONEY':
try:
norm = money(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'ORDINAL',
elif label == 'ORDINAL':
try:
norm = ordinal(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'PLAIN' nothing changes
elif label == 'PLAIN':
norm = before
out.write('"' + norm + '"')
#'PUNCT',
elif label == 'PUNCT':
norm = before
out.write('"' + norm + '"')
#'TELEPHONE',
elif label == 'TELEPHONE':
try:
norm = telephone(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'TIME',
elif label == 'TIME':
try:
norm = time(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
#'VERBATIM'
elif label == 'VERBATIM':
try:
norm = verbatim(before)
out.write('"' + norm + '"')
changes += 1
except:
out.write('"' + line + '"')
else:
print(line)
# actually there are only four inches not appeared
if len(line) > 1:
val = line.split(',')
# number with at most 1 ','
if len(val) == 2 and val[0].isdigit() and val[1].isdigit():
line = ''.join(val)
if line.isdigit():
srtd = line.translate(SUB)
srtd = srtd.translate(SUP)
srtd = srtd.translate(OTH)
out.write('"' + num2words(float(srtd)) + '"')
changes += 1
elif len(line.split(' ')) > 1:
val = line.split(' ')
for i, v in enumerate(val):
if v.isdigit():
srtd = v.translate(SUB)
srtd = srtd.translate(SUP)
srtd = srtd.translate(OTH)
val[i] = num2words(float(srtd))
# measure
elif v in sdict:
val[i] = sdict[v]
out.write('"' + ' '.join(val) + '"')
changes += 1
elif re.match(INCH_TMP, line):
line = INCH_transform(line)
print(line)
out.write('"' + line + '"')
changes += 1
else:
out.write('"' + line + '"')
out.write('\n')
total += 1
print('Total: {} Changed: {}'.format(total, changes))
test.close()
out.close()
with open('output/ambi_class.json', 'w', encoding='utf8') as f:
f.write(json.dumps(m, ensure_ascii=False, indent=4))
test()