To save a given NLTK tree to an image file (OS-agnostic), I recommend the Constituent-Treelib library, which builds on benepar, spaCy and NLTK. First, install it via pip install constituent-treelib
Then, perform the following steps:
from nltk import Tree
from constituent_treelib import ConstituentTree
# Define your sentence that should be parsed and saved to a file
sentence = "At least nine tenths of the students passed."
# Rather than a raw string you can also provide an already constructed NLTK tree
sentence = Tree('S', [Tree('NP', [Tree('NP', [Tree('QP', [Tree('ADVP', [Tree('RB', ['At']), Tree('RBS', ['least'])]), Tree('CD', ['nine'])]), Tree('NNS', ['tenths'])]), Tree('PP', [Tree('IN', ['of']), Tree('NP', [Tree('DT', ['the']), Tree('NNS', ['students'])])])]), Tree('VP', [Tree('VBD', ['passed'])]), Tree('.', ['.'])])
# Define the language that should be considered with respect to the underlying benepar and spaCy models
language = ConstituentTree.Language.English
# You can also specify the desired model for the language ("Small" is selected by default)
spacy_model_size = ConstituentTree.SpacyModelSize.Large
# Create the neccesary NLP pipeline (required to instantiate a ConstituentTree object)
nlp = ConstituentTree.create_pipeline(language, spacy_model_size)
# In case you haven't downloaded the required benepar an spaCy models, you can tell the method to do it automatically for you
# nlp = ConstituentTree.create_pipeline(language, spacy_model_size, download_models=True)
# Instantiate a ConstituentTree object and pass it the sentence as well as the NLP pipeline
tree = ConstituentTree(sentence, nlp)
# Now you can export the tree to a file (e.g., a PDF)
tree.export_tree("NLTK_parse_tree.pdf", verbose=True)
>>> PDF-file successfully saved to: NLTK_parse_tree.pdf
Result...