Programmer_nltk
Programmer_nltk

Reputation: 915

Calling output within Tree.Fromstring

from stat_parser import Parser
sent = "Open the door"
print parser.parse(sent)

from nltk import Tree
t = Tree.fromstring("(RRC (ADJP (JJ open)) (NP (DT the) (NN door)))")
grammar_from_parse = "\n".join([rule.unicode_repr() for rule in t.productions()])
print grammar_from_parse

The code above outputs

(RRC (ADJP (JJ open)) (NP (DT the) (NN door)))

RRC -> ADJP NP

ADJP -> JJ

JJ -> 'open'

NP -> DT NN

DT -> 'the'

NN -> 'door'

Is it possible to call stat_parser output the one that is bold within Tree.fromstring.

Although they are the same,Idea is to avoid copy pasting it to Tree.fromstring.

Does CFG.fromstring also accepts other CFG output within?

grammar = CFG.fromstring(""" output """)

Upvotes: 0

Views: 136

Answers (1)

RAVI
RAVI

Reputation: 3153

You just need to convert parse output to str().

from stat_parser import Parser
from nltk import Tree, CFG, RecursiveDescentParser

sent = "open the door"
parser = Parser()
print parser.parse(sent)

t = Tree.fromstring(str(parser.parse(sent)))
grammar_from_parse = "\n".join([rule.unicode_repr() for rule in t.productions()])
print grammar_from_parse
grammar = CFG.fromstring(grammar_from_parse)

rd_parser = RecursiveDescentParser(grammar)
for tree in rd_parser.parse(sent.split()):
    print(tree)

Upvotes: 1

Related Questions