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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Rico Sennrich
# extract 5 vocabulary files from parsed corpus in moses XML format
from __future__ import print_function, unicode_literals, division
import sys
import codecs
import argparse
from collections import Counter
from textwrap import dedent
# hack for python2/3 compatibility
from io import open
argparse.open = open
try:
from lxml import etree as ET
except ImportError:
from xml.etree import cElementTree as ET
HELP_TEXT = dedent("""\
generate 5 vocabulary files from parsed corpus in moses XML format
[PREFIX].special: around 40 symbols reserved for RDLM
[PREFIX].preterminals: preterminal symbols
[PREFIX].nonterminals: nonterminal symbols (which are not preterminal)
[PREFIX].terminals: terminal symbols
[PREFIX].all: all of the above
""")
def create_parser():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=HELP_TEXT)
parser.add_argument(
'--input', '-i', type=argparse.FileType('r'), default=sys.stdin,
metavar='PATH',
help="Input text (default: standard input).")
parser.add_argument(
'--output', '-o', type=str, default='vocab', metavar='PREFIX',
help="Output prefix (default: 'vocab')")
parser.add_argument(
'--ptkvz', action="store_true",
help=(
"Special rule for German dependency trees: attach separable "
"verb prefixes to verb."))
return parser
def escape_text(s):
s = s.replace('|', '|') # factor separator
s = s.replace('[', '[') # syntax non-terminal
s = s.replace(']', ']') # syntax non-terminal
s = s.replace('\'', ''') # xml special character
s = s.replace('"', '"') # xml special character
return s
def get_head(xml, args):
"""Deterministic heuristic to get head of subtree."""
head = None
preterminal = None
for child in xml:
if not len(child):
if head is not None:
continue
preterminal = child.get('label')
head = escape_text(child.text.strip())
elif args.ptkvz and head and child.get('label') == 'avz':
for grandchild in child:
if grandchild.get('label') == 'PTKVZ':
head = escape_text(grandchild.text.strip()) + head
break
return head, preterminal
def get_vocab(xml, args):
if len(xml):
head, preterminal = get_head(xml, args)
if not head:
head = '<null>'
preterminal = '<null>'
heads[head] += 1
preterminals[preterminal] += 1
label = xml.get('label')
nonterminals[label] += 1
for child in xml:
if not len(child):
continue
get_vocab(child, args)
def main(args):
global heads
global preterminals
global nonterminals
heads = Counter()
preterminals = Counter()
nonterminals = Counter()
i = 0
for line in args.input:
if i and not i % 50000:
sys.stderr.write('.')
if i and not i % 1000000:
sys.stderr.write('{0}\n'.format(i))
if line == '\n':
continue
xml = ET.fromstring(line)
get_vocab(xml, args)
i += 1
special_tokens = [
'<unk>',
'<null>',
'<null_label>',
'<null_head>',
'<head_label>',
'<root_label>',
'<start_label>',
'<stop_label>',
'<head_head>',
'<root_head>',
'<start_head>',
'<dummy_head>',
'<stop_head>',
]
for i in range(30):
special_tokens.append('<null_{0}>'.format(i))
f = open(args.output + '.special', 'w', encoding='UTF-8')
for item in special_tokens:
f.write(item + '\n')
f.close()
f = open(args.output + '.preterminals', 'w', encoding='UTF-8')
for item in sorted(preterminals, key=preterminals.get, reverse=True):
f.write(item + '\n')
f.close()
f = open(args.output + '.nonterminals', 'w', encoding='UTF-8')
for item in sorted(nonterminals, key=nonterminals.get, reverse=True):
f.write(item + '\n')
f.close()
f = open(args.output + '.terminals', 'w', encoding='UTF-8')
for item in sorted(heads, key=heads.get, reverse=True):
f.write(item + '\n')
f.close()
f = open(args.output + '.all', 'w', encoding='UTF-8')
special_tokens_set = set(special_tokens)
for item in sorted(nonterminals, key=nonterminals.get, reverse=True):
if item not in special_tokens:
special_tokens.append(item)
special_tokens_set.add(item)
for item in sorted(preterminals, key=preterminals.get, reverse=True):
if item not in special_tokens:
special_tokens.append(item)
special_tokens_set.add(item)
for item in special_tokens:
f.write(item + '\n')
i = len(special_tokens)
for item in sorted(heads, key=heads.get, reverse=True):
if item in special_tokens_set:
continue
i += 1
f.write(item + '\n')
f.close()
if __name__ == '__main__':
if sys.version_info < (3, 0):
sys.stderr = codecs.getwriter('UTF-8')(sys.stderr)
sys.stdout = codecs.getwriter('UTF-8')(sys.stdout)
sys.stdin = codecs.getreader('UTF-8')(sys.stdin)
parser = create_parser()
args = parser.parse_args()
main(args)
|