将python NLTK解析树保存到图像文件 [英] Saving python NLTK parse tree to image file

查看:100
本文介绍了将python NLTK解析树保存到图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能会复制此stackoverflow 问题.但是,我面临着一个不同的问题.这是我的工作代码.

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

这将为所有句子一一生成解析树.实际上,在我的"test.txt"中,我有100多个句子.因此,将每个文件手动保存到.ps文件确实很困难.我该如何修改代码以将这些树保存到带有标签的单个.ps或.png文件中(例如:1.png,2.png ...).这意味着我需要获取多个图像文件. 预先感谢.

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.

推荐答案

尽管这是

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

给出result树对象:

>>> 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')])])

现在执行此操作:

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

然后您会看到tree.ps文件出现在当前目录中.

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

这篇关于将python NLTK解析树保存到图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆