Saving python NLTK parse tree to image file [duplicate]

一个人想着一个人 提交于 2019-12-11 11:40:58

问题


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()

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.


回答1:


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.



来源:https://stackoverflow.com/questions/35115282/saving-python-nltk-parse-tree-to-image-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!