The documentation provides a pprint()
method that flattens the tree into one line.
Parsing this sentence:
string = "My name is Ross and I am cool. What's going on world? I'm looking for friends."
And then calling pprint()
yields the following:
u"(NP+SBAR+S\n (S\n (NP (PRP$ my) (NN name))\n (VP\n (VBZ is)\n (NP (NNP Ross) (CC and) (PRP I) (JJ am) (NN cool.))\n (SBAR\n (WHNP (WP What))\n (S+VP (VBZ 's) (VBG going) (NP (IN on) (NN world)))))\n (. ?))\n (S\n (NP (PRP I))\n (VP (VBP 'm) (VBG looking) (PP (IN for) (NP (NNS friends))))\n (. .)))"
From this point, if you wish to remove the tabs and newlines, you can use the following split
and join
(see here):
splitted = tree.pprint().split()
flat_tree = ' '.join(splitted)
Executing that yields this for me:
u"(NP+SBAR+S (S (NP (PRP$ my) (NN name)) (VP (VBZ is) (NP (NNP Ross) (CC and) (PRP I) (JJ am) (NN cool.)) (SBAR (WHNP (WP What)) (S+VP (VBZ 's) (VBG going) (NP (IN on) (NN world))))) (. ?)) (S (NP (PRP I)) (VP (VBP 'm) (VBG looking) (PP (IN for) (NP (NNS friends)))) (. .)))"