Skip to content

Commit 20ecaa2

Browse files
spottedMetalspottedMetal
authored andcommitted
Added trivial grammar E_NP_ for testing.
Fixed error in Chart parses method, where it would incorrectly return some parses that did not start at the beginning of the input (and therefore did not span the whole input).
1 parent 551af9a commit 20ecaa2

1 file changed

Lines changed: 13 additions & 2 deletions

File tree

nlp.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,11 @@ def __repr__(self):
7878
V = 'saw | liked | feel'
7979
))
8080

81+
E_NP_ = Grammar('E_NP_', # another trivial grammar for testing
82+
Rules(NP = 'Adj NP | N'),
83+
Lexicon(Adj = 'happy | handsome | hairy',
84+
N = 'man'))
85+
8186
def generate_random(grammar=E_, s='S'):
8287
"""Replace each token in s by a random entry in grammar (recursively).
8388
This is useful for testing a grammar, e.g. generate_random(E_)"""
@@ -113,14 +118,20 @@ def __init__(self, grammar, trace=False):
113118
update(self, grammar=grammar, trace=trace)
114119

115120
def parses(self, words, S='S'):
116-
"""Return a list of parses; words can be a list or string."""
121+
"""Return a list of parses; words can be a list or string.
122+
>>> chart = Chart(E_NP_)
123+
>>> chart.parses('happy man', 'NP')
124+
[[0, 2, 'NP', [('Adj', 'happy'), [1, 2, 'NP', [('N', 'man')], []]], []]]
125+
"""
117126
if isinstance(words, str):
118127
words = words.split()
119128
self.parse(words, S)
120129
# Return all the parses that span the whole input
130+
# 'span the whole input' => begin at 0, end at len(words)
121131
return [[i, j, S, found, []]
122132
for (i, j, lhs, found, expects) in self.chart[len(words)]
123-
if lhs == S and expects == []]
133+
# assert j == len(words)
134+
if i == 0 and lhs == S and expects == []]
124135

125136
def parse(self, words, S='S'):
126137
"""Parse a list of words; according to the grammar.

0 commit comments

Comments
 (0)