我已經從atis語法生成了語法,現在我想添加一些我自己的規則,特別是句子終端,我可以這樣做嗎?NLTK:我可以將終端添加到已經生成的語法中
import nltk
grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
到grammar
我想添加更多終端。
我已經從atis語法生成了語法,現在我想添加一些我自己的規則,特別是句子終端,我可以這樣做嗎?NLTK:我可以將終端添加到已經生成的語法中
import nltk
grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
到grammar
我想添加更多終端。
總之:是的,它是可能的,但你會在痛苦的赫克得到的,它更容易使用atis.cfg
作爲基礎,然後讀取新的文本文件CFG重寫你的CFG。它更容易,而不是重新分配每一個新的終端,以正確的非終端映射它們
在長,請參閱以下
首先,讓我們看看在NLTK一個CFG語法是什麼,它包含:
>>> 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']
有關詳細信息,請參閱https://github.com/nltk/nltk/blob/develop/nltk/grammar.py#L421
好像端子和非終端是Production
類型,參見https://github.com/nltk/nltk/blob/develop/nltk/grammar.py#L236,即
語法生成。每個生產將「左側」上的一個符號 映射到「右側」上的符號序列上。 (在上下文無關的情況下, 的左側必須是
Nonterminal
,右側的 一側是一系列終端,Nonterminals
。) 「終端」可以是任何不可變的可哈希對象,即 不是Nonterminal
。通常,終端是表示單詞的字符串 ,例如"dog"
或"under"
。
那麼讓我們來看看語法如何存儲的作品:
>>> type(g._productions)
<type 'list'>
>>> g._productions[-1]
zero -> 'zero'
>>> type(g._productions[-1])
<class 'nltk.grammar.Production'>
所以,現在,好像我們只能創建nltk.grammar.Production
對象,並把它們添加到grammar._productions
。
讓我們嘗試與原來的語法:
>>> 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 .)))
原來的語法不具備終端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'".
之前,我們嘗試添加singapore
到語法,讓我們看看如何detroit
存儲在語法中:
>>> 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]
所以現在我們可以嘗試重新創建singapore
相同Production
對象:
# 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)
但它仍然沒有工作,但導致給終端本身並不真正幫助它涉及到CFG,因此新加坡的休息仍然沒有語法分析:
>>> 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'".
從下面我們知道,新加坡是像底特律和底特律導致這個左handside LHS NOUN_NP -> detroit
:
>>> original_grammar._rhs_index[original_grammar._rhs_index['detroit'][0]._lhs]
[NOUN_NP -> detroit, NOUN_NP -> detroit minneapolis toronto]
所以我們需要做的是,要麼添加另一個生產爲新加坡,導致NOUN_NP
終結符號或我們的新加坡LHS追加到NOUN_NP非終結符右手邊:
>>> lhs = nltk.grammar.Nonterminal('singapore')
>>> rhs = [u'singapore']
>>> singapore_production = nltk.grammar.Production(lhs, rhs)
>>> new_grammar._productions.append(singapore_production)
現在讓我們添加新的生產NOUN_NP -> singapore
:
lhs2 = nltk.grammar.Nonterminal('NOUN_NP')
new_grammar._productions.append(nltk.grammar.Production(lhs2, [lhs]))
現在我們應該期待我們的解析器可以工作:
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'".
但它看起來像語法仍然沒有認識到我們已經添加了新的終端和非終結符,所以讓我們嘗試一個黑客和輸出我們的新的語法轉換爲字符串,並創建一個新的語法從輸出字符串:
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 .)))