I want to chunk the string to get the groups in a certain height. The original order should be kept and it should also be completly contain all the original words.
import nltk
height = 2
sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"), ("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")]
pattern = """NP: {<DT>?<JJ>*<NN>}
VBD: {<VBD>}
IN: {<IN>}"""
NPChunker = nltk.RegexpParser(pattern)
result = NPChunker.parse(sentence)
In [29]: Tree.fromstring(str(result)).pretty_print()
S
_________________|_____________________________
NP VBD IN NP
________|_________________ | | _____|____
the/DT little/JJ yellow/JJ dog/NN barked/VBD at/IN the/DT cat/NN
My approach is kind of brute force like below:
In [30]: [list(map(lambda x: x[0], _tree.leaves())) for _tree in result.subtrees(lambda x: x.height()==height)]
Out[30]: [['the', 'little', 'yellow', 'dog'], ['barked'], ['at'], ['the', 'cat']]
I thought there should exist some direct API or something I can use to do chuncking. Any suggestions are highly appreciated.