问题
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