-
Notifications
You must be signed in to change notification settings - Fork 17
/
normalize_mwe_numbering.py
executable file
·59 lines (50 loc) · 2 KB
/
normalize_mwe_numbering.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
#!/usr/bin/env python3
"""
Given a .conllulex file, apply a consistent ordering to MWEs based
primarily on the first token offset in each expression,
and secondarily on strong vs. weak (strong comes before weak).
Args: inputfile
@since: 2019-06-22
@author: Nathan Schneider (@nschneid)
"""
import os, sys, fileinput, re, json, csv
from collections import defaultdict
from itertools import chain
from conllulex2json import load_sents, print_json
inFname, = sys.argv[1:]
nSentsRenumbered = 0
nMWEsRenumbered = 0
with open(inFname, encoding='utf-8') as inF:
sents = list(load_sents(inF))
for sent in sents:
smwes = sent["smwes"]
wmwes = sent["wmwes"]
allmwes = []
for oldnum,e in smwes.items():
allmwes.append((e["toknums"][0], 's', oldnum))
for oldnum,e in wmwes.items():
allmwes.append((e["toknums"][0], 'w', oldnum))
allmwes.sort()
current_sort = sorted(allmwes, key=lambda x: x[2])
if allmwes!=current_sort:
nSentsRenumbered += 1
# renumber
new_smwes = {}
new_wmwes = {}
for newnum,(tok1,s_or_w,oldnum) in enumerate(allmwes, start=1):
if oldnum!=newnum:
nMWEsRenumbered += 1
old_container = smwes if s_or_w=='s' else wmwes
new_container = new_smwes if s_or_w=='s' else new_wmwes
e = new_container[newnum] = old_container[oldnum]
# update pointers from tokens
for toknum in e["toknums"]:
pointer, position = sent["toks"][toknum-1][s_or_w+"mwe"]
assert pointer==oldnum
sent["toks"][toknum-1][s_or_w+"mwe"] = newnum, position
assert len(new_smwes)==len(smwes)
assert len(new_wmwes)==len(wmwes)
sent["smwes"] = new_smwes
sent["wmwes"] = new_wmwes
print_json(sents)
print(f'Renumbered {nMWEsRenumbered} MWEs in {nSentsRenumbered} sentences', file=sys.stderr)