0

I use Stanford coreNLP for generating dependency tree, but I cannot store the result as it uses print function to show the tree. For instance, the code and the dependency tree for "I ask a question in StackOverFlow" would be like this:

nlp = StanfordCoreNLP('.')
parser=nlp.parse("I ask a question in StackOverFlow") 
tree=Tree.fromstring(parser.__str__()) 
tree.pretty_print()

enter image description here

Here I used Snipping Tool to take a screenshot of the generated tree manually, but in my code I will generate more than thousand trees, which is impossible to take screenshots from all of them. Any kind of help would be appreciated.

amiref
  • 3,181
  • 7
  • 38
  • 62
  • 1
    Sounds like you're looking to redirect `stdout`. Read this: https://stackoverflow.com/questions/1218933/can-i-redirect-the-stdout-in-python-into-some-sort-of-string-buffer – mypetlion Oct 17 '18 at 16:54
  • Possible duplicate of [Can I redirect the stdout in python into some sort of string buffer?](https://stackoverflow.com/questions/1218933/can-i-redirect-the-stdout-in-python-into-some-sort-of-string-buffer) – dawg Oct 17 '18 at 17:50

1 Answers1

1

On a UNIX-based system you can do:

parse.py

nlp = StanfordCoreNLP('.')
for i in range(len(sentences)):
    sentence = sentences[i]
    parser=nlp.parse(sentence) 
    tree=Tree.fromstring(parser.__str__())
    print(i, sentence)
    print('parse tree:')
    tree.pretty_print()
    print()

and do sth like python parse.py > parse_trees and your output file parse_trees will be structured as:

[index] [sentence]
parse tree:
[parse tree]

[index] [sentence]
parse tree:
[parse tree]

...
Kevin He
  • 1,210
  • 8
  • 19