In short: yes it is possible but you will get through a heck of pain, it's easier to rewrite your CFG using the atis.cfg
as a base then read the new CFG textfile. It's easier than to reassign each new terminal to the correct non-terminal to map them
In long, see the following
First let's look at what a CFG grammar in NLTK is and what it contains:
>>> import nltk
>>> g = nltk.data.load('grammars/large_grammars/atis.cfg')
>>> dir(g)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', '_all_unary_are_lexical', '_calculate_grammar_forms', '_calculate_indexes', '_calculate_leftcorners', '_categories', '_empty_index', '_immediate_leftcorner_categories', '_immediate_leftcorner_words', '_is_lexical', '_is_nonlexical', '_leftcorner_parents', '_leftcorner_words', '_leftcorners', '_lexical_index', '_lhs_index', '_max_len', '_min_len', '_productions', '_rhs_index', '_start', 'check_coverage', 'fromstring', 'is_binarised', 'is_chomsky_normal_form', 'is_flexible_chomsky_normal_form', 'is_leftcorner', 'is_lexical', 'is_nonempty', 'is_nonlexical', 'leftcorner_parents', 'leftcorners', 'max_len', 'min_len', 'productions', 'start', 'unicode_repr']
For more details, see https://github.com/nltk/nltk/blob/develop/nltk/grammar.py#L421
Seems like the terminals and non-terminals are of Production
type, see https://github.com/nltk/nltk/blob/develop/nltk/grammar.py#L236, i.e.
A grammar production. Each production maps a single symbol
on the "left-hand side" to a sequence of symbols on the
"right-hand side". (In the case of context-free productions,
the left-hand side must be a Nonterminal
, and the right-hand
side is a sequence of terminals and Nonterminals
.)
"terminals" can be any immutable hashable object that is
not a Nonterminal
. Typically, terminals are strings
representing words, such as "dog"
or "under"
.
So let's take a look at how the grammar stores the productions:
>>> type(g._productions)
<type 'list'>
>>> g._productions[-1]
zero -> 'zero'
>>> type(g._productions[-1])
<class 'nltk.grammar.Production'>
So now, it seems like we could just create the nltk.grammar.Production
objects and append them to the grammar._productions
.
Let's try with the original grammar:
>>> import nltk
>>> original_grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
>>> original_parser = ChartParser(original_grammar)
>>> sent = ['show', 'me', 'northwest', 'flights', 'to', 'detroit', '.']
>>> for i in original_parser.parse(sent):
... print i
... break
...
(SIGMA
(IMPR_VB
(VERB_VB (show show))
(NP_PPO
(pt_pron_ppo me)
(NAPPOS_NP (NOUN_NP (northwest northwest))))
(NP_NNS (NOUN_NNS (pt207 flights)) (PREP_IN (to to)))
(AVPNP_NP (NOUN_NP (detroit detroit)))
(pt_char_per .)))
The original grammar doesn't have the terminal singapore
:
>>> sent = ['show', 'me', 'northwest', 'flights', 'to', 'singapore', '.']
>>> for i in original_parser.parse(sent):
... print i
... break
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/api.py", line 49, in parse
return iter(self.parse_all(sent))
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1350, in parse_all
chart = self.chart_parse(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1309, in chart_parse
self._grammar.check_coverage(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/grammar.py", line 631, in check_coverage
"input words: %r." % missing)
ValueError: Grammar does not cover some of the input words: u"'singapore'".
Before we try to add singapore
into the grammar, let's see how detroit
is stored in the grammar:
>>> original_grammar._rhs_index['detroit']
[detroit -> 'detroit']
>>> type(original_grammar._rhs_index['detroit'])
<type 'list'>
>>> type(original_grammar._rhs_index['detroit'][0])
<class 'nltk.grammar.Production'>
>>> original_grammar._rhs_index['detroit'][0]._lhs
detroit
>>> original_grammar._rhs_index['detroit'][0]._rhs
(u'detroit',)
>>> type(original_grammar._rhs_index['detroit'][0]._lhs)
<class 'nltk.grammar.Nonterminal'>
>>> type(original_grammar._rhs_index['detroit'][0]._rhs)
<type 'tuple'>
>>> original_grammar._rhs_index[original_grammar._rhs_index['detroit'][0]._lhs]
[NOUN_NP -> detroit, NOUN_NP -> detroit minneapolis toronto]
So now we can try to recreate the same Production
object for singapore
:
# First let's create Non-terminal for singapore.
>>> nltk.grammar.Nonterminal('singapore')
singapore
>>> lhs = nltk.grammar.Nonterminal('singapore')
>>> rhs = [u'singapore']
# Now we can create the Production for singapore.
>>> singapore_production = nltk.grammar.Production(lhs, rhs)
# Now let's try to add this Production the grammar's list of production
>>> new_grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
>>> new_grammar._productions.append(singapore_production)
But it's still not working but cause giving the terminals itself don't really help in relating it to the rest of the CFG and hence singapore is still not parse-able:
>>> new_grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
>>> new_grammar._productions.append(singapore_production)
>>> new_parser = ChartParser(new_grammar)
>>> sent = ['show', 'me', 'northwest', 'flights', 'to', 'singapore', '.']
>>> new_parser.parse(sent)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/api.py", line 49, in parse
return iter(self.parse_all(sent))
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1350, in parse_all
chart = self.chart_parse(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1309, in chart_parse
self._grammar.check_coverage(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/grammar.py", line 631, in check_coverage
"input words: %r." % missing)
ValueError: Grammar does not cover some of the input words: u"'singapore'".
From the following we know that singapore is like detroit, and detroit leads to this Left-handside LHS NOUN_NP -> detroit
:
>>> original_grammar._rhs_index[original_grammar._rhs_index['detroit'][0]._lhs]
[NOUN_NP -> detroit, NOUN_NP -> detroit minneapolis toronto]
So what we will need to do is to either add another production for singapore that leads to NOUN_NP
nonterminals or append our singapore LHS to the NOUN_NP nonterminals right handside:
>>> lhs = nltk.grammar.Nonterminal('singapore')
>>> rhs = [u'singapore']
>>> singapore_production = nltk.grammar.Production(lhs, rhs)
>>> new_grammar._productions.append(singapore_production)
Now let's add the new production for NOUN_NP -> singapore
:
lhs2 = nltk.grammar.Nonterminal('NOUN_NP')
new_grammar._productions.append(nltk.grammar.Production(lhs2, [lhs]))
And now we should expect our parser to work:
sent = ['show', 'me', 'northwest', 'flights', 'to', 'singapore', '.']
print new_grammar.productions()[2091]
print new_grammar.productions()[-1]
new_parser = nltk.ChartParser(new_grammar)
for i in new_parser.parse(sent):
print i
[out]:
Traceback (most recent call last):
File "test.py", line 31, in <module>
for i in new_parser.parse(sent):
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/api.py", line 49, in parse
return iter(self.parse_all(sent))
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1350, in parse_all
chart = self.chart_parse(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1309, in chart_parse
self._grammar.check_coverage(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/grammar.py", line 631, in check_coverage
"input words: %r." % missing)
ValueError: Grammar does not cover some of the input words: u"'singapore'".
But it looks like the grammar is still not recognizing the new terminals and nonterminals we've added, so let's try a hack and output our new grammar into string and create a newer grammar from the output string:
import nltk
lhs = nltk.grammar.Nonterminal('singapore')
rhs = [u'singapore']
singapore_production = nltk.grammar.Production(lhs, rhs)
new_grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
new_grammar._productions.append(singapore_production)
lhs2 = nltk.grammar.Nonterminal('NOUN_NP')
new_grammar._productions.append(nltk.grammar.Production(lhs2, [lhs]))
# Create newer grammar from new_grammar's string
newer_grammar = nltk.grammar.CFG.fromstring(str(new_grammar).split('\n')[1:])
# Reassign new_grammar's string to newer_grammar !!!
newer_grammar._start = new_grammar.start()
newer_grammar
sent = ['show', 'me', 'northwest', 'flights', 'to', 'singapore', '.']
print newer_grammar.productions()[2091]
print newer_grammar.productions()[-1]
newer_parser = nltk.ChartParser(newer_grammar)
for i in newer_parser.parse(sent):
print i
break
[out]:
(SIGMA
(IMPR_VB
(VERB_VB (show show))
(NP_PPO
(pt_pron_ppo me)
(NAPPOS_NP (NOUN_NP (northwest northwest))))
(NP_NNS (NOUN_NNS (pt207 flights)) (PREP_IN (to to)))
(AVPNP_NP (NOUN_NP (singapore singapore)))
(pt_char_per .)))