简体   繁体   中英

Add conjunction to grammar rule - NLTK parse into syntax tree in python

Suppose we have following incomplete grammar rule:

grammar2 = nltk.parse_cfg("""
S -> NP VP
NP -> Det N
VP -> V NP
PN -> 'David' 
Det -> 'the'
N -> 'man' 
V -> 'saw' | 'helped' 
Pro -> 'him'
Conj -> 'and'
""")

I want to create syntax tree for following sentence:

sent = ['the', 'man', 'saw', 'David', 'and', 'helped', 'him']
parser = nltk.ChartParser(grammar2)
trees = parser.nbest_parse(sent)
for tree in trees:
    print tree

But I don't know how can I add conjunction and in the grammar?

A job for recursion. This should work.

S -> NP VP 
VP -> V NP | V NP Conj VP
NP -> Det N | PN | Pro
PN -> 'David' 
Det -> 'the'
N -> 'man' 
V -> 'saw' | 'helped' 
Pro -> 'him'
Conj -> 'and'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM