Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving python NLTK parse tree to image file [duplicate]

This might replicate this stackoverflow question . However, i'm facing a different problem. This is my working code.

import nltk 
from textblob import TextBlob
with open('test.txt', 'rU') as ins:
    array = []
    for line in ins:
        array.append(line)
for i in array:
    wiki = TextBlob(i)
    a=wiki.tags
    sentence = a
    pattern = """NP: {<DT>?<JJ>*<NN>}
    VBD: {<VBD>}
    IN: {<IN>}"""
    NPChunker = nltk.RegexpParser(pattern)
    result = NPChunker.parse(sentence)

    result.draw()

enter image description here This produce parse trees one by one for all the sentences. Actually in my "test.txt" i have more than 100 sentences. therefore, it's really hard to save each file into .ps files manually. How could i modify my code to save this trees to single .ps or .png files with a label (something like: 1.png,2.png ...).That mean i need to get more than one image files. thanks in advance.

like image 762
miller Avatar asked Nov 25 '25 08:11

miller


1 Answers

Although this is a duplicated question from Saving nltk drawn parse tree to image file, here's a simpler answer.

Given the result Tree object:

>>> import nltk
>>> from nltk import pos_tag
>>> pattern = """NP: {<DT>?<JJ>*<NN>}
... VBD: {<VBD>}
... IN: {<IN>}"""
>>> NPChunker = nltk.RegexpParser(pattern)
>>> sentence = 'criminal lawyer new york'.split()
>>> pos_tag(sentence)
[('criminal', 'JJ'), ('lawyer', 'NN'), ('new', 'JJ'), ('york', 'NN')]
>>> result = NPChunker.parse(pos_tag(sentence))
>>> result
Tree('S', [Tree('NP', [('criminal', 'JJ'), ('lawyer', 'NN')]), Tree('NP', [('new', 'JJ'), ('york', 'NN')])])

Now do this:

>>> from nltk.draw.tree import TreeView
>>> TreeView(result)._cframe.print_to_file('tree.ps')

Then you will see the tree.ps file appears in the current directory.

like image 128
alvas Avatar answered Nov 26 '25 22:11

alvas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!