如何提取括号内语法产生式规则?

2024-04-29 03:30:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个例句。”打开门。”我解析了一个句子,得到了括号内的解析输出,如下所示。在

(S (VP (VB open) (NP (DT the) (NN door))) (. .))

我需要提取产生解析输出的CFG语法规则。 我可以手动写出:

grammar = CFG.fromstring("""   
S -> VP NP   
NP -> Det N   
VP -> V   
Det ->'the '   
N -> 'door'   
V -> 'Open'   
""")  

但是这很费时,我如何生成括号中自动解析的语法规则?在


Tags: the规则npdt语法nnopencfg
2条回答

如果要从括号中解析创建规则,可以使用^{}

>>> from nltk import Tree
>>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
>>> t.productions()
[S -> NP VP, NP -> D N, D -> 'the', N -> 'dog', VP -> V NP, V -> 'chased', NP -> D N, D -> 'the', N -> 'cat']

Tree.productions()将返回^{}对象的列表:

^{pr2}$

要将规则转换为字符串形式,请使用Production.unicode_repr

>>> t.productions()[0].unicode_repr()
u'S -> NP VP'

要获得括号内语法的字符串表示,请执行以下操作:

>>> from nltk import Tree
>>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
>>> grammar_from_parse = "\n".join([rule.unicode_repr() for rule in t.productions()])
>>> print grammar_from_parse
S -> NP VP
NP -> D N
D -> 'the'
N -> 'dog'
VP -> V NP
V -> 'chased'
NP -> D N
D -> 'the'
N -> 'cat'

你可以使用树.生产()从树中获取CFG规则的方法。在

示例:

from nltk import Tree

t = Tree.fromstring("(S (VP (VB open) (NP (DT the) (NN door))) (. .))")
print t.productions()

输出:

^{pr2}$

有关详细信息,请查看-NLTK Tree Productions

相关问题 更多 >