-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyCharty.py
305 lines (243 loc) · 9.14 KB
/
MyCharty.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
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
ChartyPy3.py
This is a small incremental bottom-up chart parser for context free grammars.
(C) 2005-2011 by Damir Cavar <[email protected]>
This code is written and distributed under the
Lesser GNU General Public License version 3 or newer.
See http://www.gnu.org/copyleft/lesser.html for details
on the license or the the file lgpl-3.0.txt that should always be
distributed with this code.
Used data structures:
chart:
list of edges
edge:
list of integers and symbols
[start, end, dotindex, LHS, RHS]
start: integer, start of the edge
end: integer, end of the edge
dotindex: integer, position of the dot in the RHS
LHS: string, left-hand side symbol
RHS: list of strings, symbols in right-hand side
Properties:
Incremental (left-to-right) bottom-up chart parser.
Select only potentially appropriate rules from grammar
- length of RHS is less or equal to remaining words/symbols
Processing steps:
Word by word:
Initialise chart with word (add edge for word)
Do until no further improvement:
Add new rules from grammar that consume inactive edges
Apply the fundamental rule to induce new edges
Calling via command line:
If ChartyPy3.py is made executable, one can call it:
./ChartyPy3.py -g PSG1.txt -i "John loves Mary"
or start Python with the script otherwise:
python ChartyPy3.py -g PSG1.txt -i "John loves Mary"
Start the script with as:
python ChartyPy3.py -h
for instructions about the parameters.
This code can be opimized. However, its main purpose is to help students understand a simple algorithm for chart parsing. If there are any bugs, please let me know:
Damir Cavar <[email protected]>
"""
__author__ = "Damir Cavar <[email protected]>"
__date__ = "$May 29, 2005 10:36:30 AM$"
__version__ = "0.5"
import sys, PSGParse3
import argparse
import codecs
DEBUG = False # set this to 0 if you do not want tracking
QTREE = False
def isActive(edge):
"""Return 1 if edge is active, else return 0."""
if edge[2] < len(edge[4]): return True
return False
def isInactive(edge):
"""Return True if edge is active, else returns False."""
if edge[2] >= len(edge[4]): return True
return False
def match(aedge, iedge):
"""Returns True if the active edge and the inactive edge match,
otherwise False.
"""
if aedge[1] == iedge[0]:
if aedge[4][aedge[2]] == iedge[3]: return True
return False
def getParse(inputlength, chart, grammar):
"""Returns a list of all parses in bracketing notation."""
parses = []
for i in range(len(chart)):
if not isActive(chart[i]):
if chart[i][0] == 0 and chart[i][1] == inputlength: # got spanning edge
parses.append(struct2Str(i, chart, grammar))
return parses
def getQtreeParse(inputlength, chart, grammar):
"""Returns a list of all parses in bracketing notation."""
parses = []
for i in range(len(chart)):
if not isActive(chart[i]):
if chart[i][0] == 0 and chart[i][1] == inputlength: # got spanning edge
parses.append(" ".join(("\Tree", struct2QtreeStr(i, chart, grammar))))
return parses
def struct2Str(edge, chart, grammar):
"""Returns a string representation of the parse with
labled brackets.
Parameters:
edges - the lsit of edges that make a parse
chart - the current chart (list of edges)
"""
tmpstr = ""
edgenums = chart[edge][5]
tmpstr = "".join((tmpstr, "[", grammar.id2s(chart[edge][3])))
for x in chart[edge][4]:
if grammar.isTerminal(x):
tmpstr = " ".join( (tmpstr, grammar.id2s(x)) )
else:
tmpstr = " ".join( (tmpstr, struct2Str(edgenums[0], chart, grammar)) )
edgenums = edgenums[1:]
tmpstr = "".join( (tmpstr, " ]") )
return tmpstr
def struct2QtreeStr(edge, chart, grammar):
"""Returns a string representation of the parse with
labled brackets.
Parameters:
edges - the lsit of edges that make a parse
chart - the current chart (list of edges)
"""
tmpstr = ""
edgenums = chart[edge][5]
tmpstr = "".join((tmpstr, "[.", grammar.id2s(chart[edge][3])))
for x in chart[edge][4]:
if grammar.isTerminal(x):
tmpstr = " ".join( (tmpstr, grammar.id2s(x)) )
else:
tmpstr = " ".join( (tmpstr, struct2QtreeStr(edgenums[0], chart, grammar)) )
edgenums = edgenums[1:]
tmpstr = "".join( (tmpstr, " ]") )
return tmpstr
def edgeStr(edge, grammar):
""" """
return str( (edge[0], edge[1], edge[2],
grammar.id2s(edge[3]),
grammar.idl2s(edge[4]),
edge[5]) )
def ruleInvocation(lststart, chart, inputlength, grammar):
"""Add all the rules of the grammar to the chart that
are relavant:
Find the rule with the LHS of edge as the leftmost RHS
symbol and maximally the remaining length of the input.
Parameters:
lststart - start position at edge in chart
chart - the current chart
inputlength - the length of the input sentence
grammar - the grammar object raturned by PSGParse3
"""
change = False
for i in range(lststart, len(chart)):
if chart[i][2] >= len(chart[i][4]): # only inactive edge
(start, end, index, lhs, rhs, consumed) = chart[i]
for k in grammar.rhshash.get(lhs, ()):
if len(k[1]) > inputlength - start:
continue
newedge = ( start, end, 1, k[0], k[1], (i,) )
if newedge in chart:
continue
chart.append(newedge)
change = True
if DEBUG:
print("RI Adding edge:", edgeStr(newedge, grammar))
return change
def fundamentalRule(chart, grammar):
"""The fundamental rule of chart parsing generates new edges by
combining fitting active and inactive edges.
Parameters:
chart - the current chart
"""
change = False
for aedge in chart:
if isActive(aedge):
for k in range(len(chart)):
if isInactive(chart[k]):
if match(aedge, chart[k]):
newedge = (aedge[0], chart[k][1], aedge[2] + 1,
aedge[3], aedge[4], tuple(list(aedge[5]) + [ k ]))
if newedge not in chart:
chart.append(newedge)
change = True
if DEBUG:
print("FR Adding edge:", edgeStr(newedge, grammar))
return change
def parse(inp, grammar):
"""Parse a list of tokens.
Arguments:
inp = a list of tokens
grammar = an object returned by PSGParse3
"""
chart = []
inputlength = len(inp)
chartpos = 0 # remember start-position in chart
for i in range(inputlength):
# initialize with input token
rules = grammar.rhshash.get(grammar.symb2id[inp[i]], ( ("", ()) ) )
for rule in rules:
if rule[0]:
chart.append( ( i, i + 1, 1, rule[0], rule[1], () ) )
if DEBUG:
print("Adding edge:", edgeStr(chart[len(chart) - 1], grammar))
change = 1
while change:
change = 0
chartlen = len(chart)
if ruleInvocation(chartpos, chart, inputlength, grammar):
change = 1
chartpos = chartlen # set pointer to new edge in chart
if fundamentalRule(chart, grammar):
change = 1
if DEBUG:
print("Chart:")
for i in range(len(chart)):
if isActive(chart[i]):
print(i, "Active:", end=" ")
else:
print(i, "Inactive:", end=" ")
print(edgeStr(chart[i], grammar))
if QTREE:
return getQtreeParse(inputlength, chart, grammar)
return getParse(inputlength, chart, grammar)
def printParses(parses):
"""Prints the parse as brackated string to the screen."""
numparses = len(parses)
counter = 0
for i in parses:
counter += 1
print("Parse:", counter, "of", numparses)
print(i)
if __name__ == "__main__":
usage = "usage: %(prog)s [options]"
parser = argparse.ArgumentParser(prog="ChartyPy", usage=usage,
description='A chart parser, based on the Earley algorithm.',
epilog="(C) 2005-2011 by Damir Cavar <[email protected]>")
parser.add_argument("-g", "--grammar", dest="grammar", required=True,
help="name of the file with the context-free grammar")
parser.add_argument("-i", "--input", dest="sentence", required=True,
help="input sentence, e.g. \"John kissed Mary\"")
parser.add_argument("-l", "--latex", dest="latex", action="store_true",
required=False,
help="output of parse structure in LaTeX notation for qtree.sty")
parser.add_argument("-q", "--quiet",
action="store_false", dest="DEBUG", default=True,
help="don't print the chart content [default True]")
args = parser.parse_args()
if args:
DEBUG = args.DEBUG
QTREE = args.latex
try:
mygrammar = PSGParse3.PSG(args.grammar) # initialization of the grammar
except IOError:
print("Cannot load grammar:, args.grammar")
else:
fr = codecs.open(args.sentence, "r", "utf-8")
text = fr.read()
fr.close()
printParses(parse(text.split(), mygrammar))