将 python NLTK 解析树保存到图像文件[重复]

2024-05-01

这可能会复制这个 stackoverflowquestion https://stackoverflow.com/questions/23429117/saving-nltk-drawn-parse-tree-to-image-file。但是,我面临着不同的问题。这是我的工作代码。

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.


虽然这是一个重复的问题将 nltk 绘制的解析树保存到图像文件 https://stackoverflow.com/questions/23429117/saving-nltk-drawn-parse-tree-to-image-file,这是一个更简单的答案。

鉴于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文件出现在当前目录中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 python NLTK 解析树保存到图像文件[重复] 的相关文章

随机推荐