-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvua_xml_parser.py
412 lines (362 loc) · 10.6 KB
/
vua_xml_parser.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
"""
NAACL 2018 Figurative Workshop Shared Task on Metaphor Detection
Script to parse VUA XML corpus to get text fragment, sentence id, sentence text tuples.
:author: Ben Leong ([email protected])
"""
import os
from os.path import join
import csv
import configparser
import re
try:
from lxml import etree as ET
print("running with lxml.etree")
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as ET
print("running with cElementTree on Python 2.5+")
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as ET
print("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as ET
print("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as ET
print("running with ElementTree")
except ImportError:
print("Failed to import ElementTree from any known place")
TRAINING_PARTION = [
'a1e-fragment01',
# 'a1f-fragment06',
# 'a1f-fragment07',
# 'a1f-fragment08',
# 'a1f-fragment09',
# 'a1f-fragment10',
# 'a1f-fragment11',
# 'a1f-fragment12',
# 'a1g-fragment26',
# 'a1g-fragment27',
# 'a1h-fragment05',
# 'a1h-fragment06',
# 'a1j-fragment34',
# 'a1k-fragment02',
# 'a1l-fragment01',
# 'a1m-fragment01',
# 'a1n-fragment09',
# 'a1n-fragment18',
# 'a1p-fragment01',
# 'a1p-fragment03',
# 'a1x-fragment03',
# 'a1x-fragment04',
# 'a1x-fragment05',
# 'a2d-fragment05',
# 'a38-fragment01',
# 'a39-fragment01',
# 'a3c-fragment05',
# 'a3e-fragment03',
# 'a3k-fragment11',
# 'a3p-fragment09',
# 'a4d-fragment02',
# 'a6u-fragment02',
# 'a7s-fragment03',
# 'a7y-fragment03',
# 'a80-fragment15',
# 'a8m-fragment02',
# 'a8n-fragment19',
# 'a8r-fragment02',
# 'a8u-fragment14',
# 'a98-fragment03',
# 'a9j-fragment01',
# 'ab9-fragment03',
# 'ac2-fragment06',
# 'acj-fragment01',
# 'ahb-fragment51',
# 'ahc-fragment60',
# 'ahf-fragment24',
# 'ahf-fragment63',
# 'ahl-fragment02',
# 'ajf-fragment07',
# 'al0-fragment06',
# 'al2-fragment23',
# 'al5-fragment03',
# 'alp-fragment01',
# 'amm-fragment02',
# 'as6-fragment01',
# 'as6-fragment02',
# 'b1g-fragment02',
# 'bpa-fragment14',
# 'c8t-fragment01',
# 'cb5-fragment02',
# 'ccw-fragment03',
# 'cdb-fragment02',
# 'cdb-fragment04',
# 'clp-fragment01',
# 'crs-fragment01',
# 'ea7-fragment03',
# 'ew1-fragment01',
# 'fef-fragment03',
# 'fet-fragment01',
# 'fpb-fragment01',
# 'g0l-fragment01',
# 'kb7-fragment10',
# 'kbc-fragment13',
# 'kbd-fragment07',
# 'kbh-fragment01',
# 'kbh-fragment02',
# 'kbh-fragment03',
# 'kbh-fragment09',
# 'kbh-fragment41',
# 'kbj-fragment17',
# 'kbp-fragment09',
# 'kbw-fragment04',
# 'kbw-fragment11',
# 'kbw-fragment17',
# 'kbw-fragment42',
# 'kcc-fragment02',
# 'kcf-fragment14',
# 'kcu-fragment02',
'kcv-fragment42']
def read_config(configFilename):
parser = configparser.ConfigParser()
parser.read(configFilename)
xml_file = parser['params']['xml_file']
functions = set(parser['params']['functions'].split(','))
types = set(parser['params']['types'].split(','))
subtypes = set(parser['params']['subtypes'].split(','))
function_override = bool(
parser['params']['function_override'].lower() == 'true')
return xml_file, functions, types, subtypes, function_override
def is_metaphor(seg, functions, types, subtypes, function_override):
if seg is not None:
if seg.get('function') in functions:
if not function_override:
"""setup.cfg should contain:
[params]
xml_file = 2541/VUAMC.xml
functions = mrw
types = impl
subtypes = PP,WIDLII
function_override = False
"""
return 1
elif function_override:
"""setup.cfg should contain:
[params]
xml_file = 2541/VUAMC.xml
# functions = mrw
# types = met,lit,impl
# subtypes = WIDLII
function_override = True
"""
if seg.get('subtype')=="WIDLII": # although all borderline cases are of metaphor type indirect, they will be independently identified here
return 4
elif seg.get('type')=="met": # of metaphor type indirect
return 1
elif seg.get('type')=="lit": # of metaphor type direct
return 2
elif seg.get('type')=="impl": # of metaphor type implicit
return 3
else:
return 0
else:
return 0
else:
return 0
else:
return 0
def handle_anomaly(txt_id, sentence_id):
if txt_id == 'as6-fragment01' and sentence_id == '26':
return 'M_to'
if txt_id == 'as6-fragment01' and sentence_id == '89':
return 'M_sector'
if txt_id == 'kb7-fragment48' and sentence_id == '13368':
return 'like'
def extract_xml_tag_text(
txt_id,
sentence_id,
namespace,
t,
functions,
types,
subtypes,
function_override):
final_token = None
segs = t.findall('./' + namespace + 'seg')
if len(segs) > 0:
for seg in segs:
if seg.text is None:
return handle_anomaly(txt_id, sentence_id)
flag = is_metaphor(seg, functions, types, subtypes, function_override)
temp_token = seg.text.strip()
temp_token = re.sub('[\[\]]', '', temp_token) # replace non-word
if flag == 1:
temp_token = 'M_' + temp_token
temp_token = re.sub(' +', ' M_', temp_token)
elif flag == 2:
temp_token = 'L_' + temp_token
temp_token = re.sub(' +', ' L_', temp_token)
elif flag == 3:
temp_token = 'I_' + temp_token
temp_token = re.sub(' +', ' I_', temp_token)
elif flag == 4:
temp_token = 'W_' + temp_token
temp_token = re.sub(' +', ' W_', temp_token)
prefix = t.text
if prefix:
temp_token = prefix.strip() + ' ' + temp_token
suffix = seg.tail
if suffix:
temp_token = temp_token + ' ' + suffix.strip()
temp_token = re.sub(' +', ' ', temp_token)
if final_token:
final_token += temp_token.strip()
else:
final_token = temp_token.strip()
else:
try:
final_token = t.text.strip()
# replace non-word
final_token = re.sub('[\[\]]', '', final_token)
final_token = re.sub(' +', ' ', final_token)
except:
pass
if final_token and re.search(
'-',
final_token):
if re.search(
'M_',
final_token):
final_token = re.sub(' ', '', final_token)
final_token = re.sub('M_', '', final_token)
final_token = 'M_' + final_token
elif re.search(
'L_',
final_token):
final_token = re.sub(' ', '', final_token)
final_token = re.sub('L_', '', final_token)
final_token = 'L_' + final_token
elif re.search(
'I_',
final_token):
final_token = re.sub(' ', '', final_token)
final_token = re.sub('I_', '', final_token)
final_token = 'I_' + final_token
elif re.search(
'W_',
final_token):
final_token = re.sub(' ', '', final_token)
final_token = re.sub('W_', '', final_token)
final_token = 'W_' + final_token
if final_token and len(
final_token.split()) > 1 and len(
t.get('lemma').split()) == 1:
final_token = re.sub(' ', '', final_token)
# cleaning corrupted tokens due to annotator errors
if final_token and re.search('^>[A-Za-z]+', final_token):
final_token = re.sub('>', '', final_token)
if final_token and re.search('^<[A-Za-z]+', final_token):
final_token = re.sub('<', '', final_token)
if final_token and re.search('^=[A-Za-z]+', final_token):
final_token = re.sub('=', '', final_token)
if final_token and re.search('^/[A-Za-z]+', final_token):
final_token = re.sub('/', '', final_token)
return final_token
def process_sentence(
txt_id,
sentence,
tei_namespace,
functions,
types,
subtypes,
function_override):
sentence_id = sentence.get('n')
tokens_lst = []
tokens = sentence.findall('*')
for t in tokens:
# special handling of cases with embedded words/puncts within a
# <hi></hi> pair of tags
if t.tag == tei_namespace + 'hi':
subTokens = t.findall('*')
for st in subTokens:
token_text = extract_xml_tag_text(
txt_id, sentence_id,
tei_namespace, st, functions,
types, subtypes, function_override)
if token_text is None or token_text == '':
continue
tokens_lst.append(token_text.strip())
continue # done for this tag pair, continue
token_text = extract_xml_tag_text(
txt_id, sentence_id,
tei_namespace,
t,
functions,
types,
subtypes,
function_override)
# skips empty, non-meaningful tokens
if token_text is None or token_text == '':
continue
tokens_lst.append(token_text.strip())
return sentence_id, ' '.join(tokens_lst)
def extract_xml(
xml_file,
functions,
types,
subtypes,
function_override):
tei_namespace = '{http://www.tei-c.org/ns/1.0}'
xml_namespace = '{http://www.w3.org/XML/1998/namespace}'
tree = ET.parse(xml_file)
root = tree.getroot()
texts = root.findall(
'./' +
tei_namespace +
'text/' +
tei_namespace +
'group/' +
tei_namespace +
'text')
output = []
for txt in texts:
txt_id = txt.attrib[xml_namespace + 'id']
if txt_id in TRAINING_PARTION: # if txt_id not in TRAINING_PARTION:
continue #
sents = txt.findall('.//' + tei_namespace + 's')
for s in sents:
sentence_id, sentence_txt = process_sentence(
txt_id, s, tei_namespace, functions, types, subtypes, function_override)
output.append({'txt_id': txt_id,
'sentence_id': sentence_id,
'sentence_txt': sentence_txt})
return output
def main():
xml_file, functions, types, subtypes, function_override = read_config(
'setup.cfg')
output = extract_xml(
xml_file,
functions,
types,
subtypes,
function_override)
with open('vuamc_corpus_train.csv', 'w') as csvfile:
fieldnames = [
'txt_id',
'sentence_id',
'sentence_txt']
writer = csv.DictWriter(
csvfile,
fieldnames=fieldnames,
quoting=csv.QUOTE_ALL)
writer.writeheader()
writer.writerows(output)
if __name__ == '__main__':
main()