本文整理汇总了Python中nltk.draw.util.CanvasFrame.print_to_file方法的典型用法代码示例。如果您正苦于以下问题:Python CanvasFrame.print_to_file方法的具体用法?Python CanvasFrame.print_to_file怎么用?Python CanvasFrame.print_to_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nltk.draw.util.CanvasFrame
的用法示例。
在下文中一共展示了CanvasFrame.print_to_file方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: quicktree
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
def quicktree(sentence):
"""Parse a sentence and return a visual representation in IPython"""
import os
from nltk import Tree
from nltk.draw.util import CanvasFrame
from nltk.draw import TreeWidget
from stat_parser import Parser
try:
from IPython.display import display
from IPython.display import Image
except:
pass
try:
get_ipython().getoutput()
except TypeError:
have_ipython = True
except NameError:
import subprocess
have_ipython = False
parser = Parser()
parsed = parser.parse(sentence)
cf = CanvasFrame()
tc = TreeWidget(cf.canvas(),parsed)
cf.add_widget(tc,10,10) # (10,10) offsets
cf.print_to_file('tree.ps')
cf.destroy()
if have_ipython:
tregex_command = 'convert tree.ps tree.png'
result = get_ipython().getoutput(tregex_command)
else:
tregex_command = ["convert", "tree.ps", "tree.png"]
result = subprocess.check_output(tregex_command)
os.remove("tree.ps")
return Image(filename='tree.png')
os.remove("tree.png")
示例2: drawrst
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
def drawrst(strtree, fname):
""" Draw RST tree into a file
"""
if not fname.endswith(".ps"):
fname += ".ps"
cf = CanvasFrame()
t = Tree.fromstring(strtree)
tc = TreeWidget(cf.canvas(), t)
cf.add_widget(tc,10,10) # (10,10) offsets
cf.print_to_file(fname)
cf.destroy()
示例3: draw_tree
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
def draw_tree(tree_string):
raise NotImplementedError()
from nltk import Tree
from nltk.draw.util import CanvasFrame
from nltk.draw import TreeWidget
cf = CanvasFrame()
tree = Tree.fromstring(tree_string.replace('[','(').replace(']',')') )
cf.add_widget(TreeWidget(cf.canvas(), tree), 10, 10)
cf.print_to_file('tree.ps')
cf.destroy
示例4: display_tree
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
def display_tree(tree):
if nltk_is_available:
count = 0
for t in tree:
cf = CanvasFrame()
tc = TreeWidget(cf.canvas(), t)
cf.add_widget(tc, 10, 10)
count += 1
fileName = "tree" + repr(count) + ".ps"
cf.print_to_file(fileName)
cf.destroy()
else:
count = 0
for t in tree:
count += 1
fileName = "tree" + repr(count) + ".txt"
pprint.pprint(t, fileName)
示例5: execute
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
def execute(self, frase):
os.environ['STANFORD_PARSER'] = 'nltk/stanford-parser.jar'
os.environ['STANFORD_MODELS'] = 'nltk/stanford-parser-3.5.2-models.jar'
parser = stanford.StanfordParser(model_path="nltk/englishPCFG.ser.gz")
sentence = parser.raw_parse(frase)
print sentence
# GUI
for line in sentence:
cf = CanvasFrame()
tc = TreeWidget(cf.canvas(),line)
cf.add_widget(tc,40,40) # (10,10) offsets
cf.print_to_file('tree_stanford.ps')
#cf.destroy()
os.popen('convert tree_stanford.ps -resize 300% static/img/tree_stanford.png')
示例6: main
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
def main(args):
"""
Subcommand main.
You shouldn't need to call this yourself if you're using
`config_argparser`
"""
corpus = read_corpus(args)
odir = get_output_dir(args)
for key in corpus:
cframe = CanvasFrame()
widget = TreeWidget(cframe.canvas(), corpus[key])
cframe.add_widget(widget, 10, 10)
ofilename = fp.join(odir, key.doc) + '.ps'
cframe.print_to_file(ofilename)
cframe.destroy()
announce_output_dir(odir)
示例7: tagger
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
def tagger(self, frase):
#hacer el tag
text = nltk.word_tokenize(frase)
postag = nltk.pos_tag(text)
#convertirlo al formato lips
result = "("
for index in range(len(postag)):
result += "( " + postag[index][0] + " ( " + postag[index][1]+ " ) )"
result += ")"
#ejecutar bikel
#pasar resultado a archivo
#hoy = str(datetime.date.today())
f = open('prueba', 'w')
f.write(result)
f.close()
#consola = os.popen('tcsh ../dbparser/bin/parse 400 ../dbparser/settings/collins.properties ../wsj-02-21.obj.gz prueba')
args = shlex.split("tcsh ../dbparser/bin/parse 400 ../dbparser/settings/collins.properties ../wsj-02-21.obj.gz prueba")
print args
p = subprocess.Popen(args,stderr=subprocess.STDOUT)
p.wait()
f2 = open('prueba.parsed', 'r')
resultado = f2.read()
t = Tree.fromstring(resultado)
cf = CanvasFrame()
tc = TreeWidget(cf.canvas(),t)
cf.add_widget(tc,40,40) # (10,10) offsets
cf.print_to_file('tree_bikel.ps')
#cf.destroy()
os.popen('convert tree_bikel.ps -resize 300% static/img/tree_bikel.png')
return resultado
示例8: tree_to_ps
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
def tree_to_ps(s, outfile):
global _canvas_frame
if _canvas_frame is None:
_canvas_frame = CanvasFrame()
# May throw ValueError:
widget = tree_to_widget(s, _canvas_frame.canvas())
_canvas_frame.canvas()['scrollregion'] = (0, 0, 1, 1)
_canvas_frame.add_widget(widget)
_canvas_frame.print_to_file(outfile)
bbox = widget.bbox()
_canvas_frame.destroy_widget(widget)
## Testing..
#for (key, val) in metrics.items():
# print key, '\n ', val
return bbox[2:]
示例9: to_ps
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
def to_ps(self, filename):
"""Export as a PostScript image.
This function is used by `_repr_png_`.
"""
_canvas_frame = CanvasFrame()
# WIP customization of visual appearance
# NB: conda-provided python and tk cannot access most fonts on the
# system, thus it currently falls back on the default font
widget = tree_to_treesegment(_canvas_frame.canvas(), self,
tree_yspace=35,
node_font=('Verdana', -18, 'bold'),
leaf_font=('Verdana', -18))
_canvas_frame.add_widget(widget)
x, y, w, h = widget.bbox()
# print_to_file uses scrollregion to set the width and height of the
# pdf
_canvas_frame.canvas()['scrollregion'] = (0, 0, w, h)
# print to file
_canvas_frame.print_to_file(filename)
_canvas_frame.destroy_widget(widget)
示例10: ShiftReduceApp
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
#.........这里部分代码省略.........
self._lastoper2['text'] = 'Failure'
def shift(self, *e):
if self._animating_lock: return
if self._parser.shift():
tok = self._parser.stack()[-1]
self._lastoper1['text'] = 'Shift:'
self._lastoper2['text'] = '%r' % tok
if self._animate.get():
self._animate_shift()
else:
self._redraw()
return True
return False
def reduce(self, *e):
if self._animating_lock: return
production = self._parser.reduce()
if production:
self._lastoper1['text'] = 'Reduce:'
self._lastoper2['text'] = '%s' % production
if self._animate.get():
self._animate_reduce()
else:
self._redraw()
return production
def undo(self, *e):
if self._animating_lock: return
if self._parser.undo():
self._redraw()
def postscript(self, *e):
self._cframe.print_to_file()
def mainloop(self, *args, **kwargs):
"""
Enter the Tkinter mainloop. This function must be called if
this demo is created from a non-interactive program (e.g.
from a secript); otherwise, the demo will close as soon as
the script completes.
"""
if in_idle(): return
self._top.mainloop(*args, **kwargs)
#########################################
## Menubar callbacks
#########################################
def resize(self, size=None):
if size is not None: self._size.set(size)
size = self._size.get()
self._font.configure(size=-(abs(size)))
self._boldfont.configure(size=-(abs(size)))
self._sysfont.configure(size=-(abs(size)))
#self._stacklabel['font'] = ('helvetica', -size-4, 'bold')
#self._rtextlabel['font'] = ('helvetica', -size-4, 'bold')
#self._lastoper_label['font'] = ('helvetica', -size)
#self._lastoper1['font'] = ('helvetica', -size)
#self._lastoper2['font'] = ('helvetica', -size)
#self._prodlist['font'] = ('helvetica', -size)
#self._prodlist_label['font'] = ('helvetica', -size-2, 'bold')
self._redraw()
def help(self, *e):
示例11: parse
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
#-*- coding: utf8 -*-
__author__ = 'dasolma'
from parser import *
from nltk import Tree
from nltk.draw.util import CanvasFrame
from nltk.draw import TreeWidget
sentences = ["¿ Como está la luz del dormitorio ?",
"Enciende la luz de la cocina",
"configura el aire acondicionado a 26 grados a las 6 pm hasta las 7:20 am",
"Apaga el aire acondicionado",
"Apaga el horno",
"¿ Como está la puerta de la cocina ?",
"Enciende el aire acondicionado"]
count = 1
for sent in sentences:
print sent
trees = parse(sent)
if len(trees) == 0: print "No parser"
else:
for t in trees:
cf = CanvasFrame()
tc = TreeWidget(cf.canvas(),t)
cf.add_widget(tc,10,10) # (10,10) offsets
cf.print_to_file('tree%d.ps'%count)
cf.destroy()
count +=1
示例12: in
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
low = sys.argv[1].lower()
# then chop off the punctuation
# http://stackoverflow.com/questions/16050952/how-to-remove-all-the-punctuation-in-a-string-python
lower = "".join(c for c in low if c not in ('!', '.', '?'))
# generate the parse tree for the sentence they inputed
trees = generate_parse_tree(lower, get_grammar(sys.argv[2]))
# print type(trees)
numTrees = 0
for tree in trees:
if numTrees >= MAX_TREES:
break
# if the tree is an error tree, continue to the next one
# print tree
if tree == "Error":
continue
# print "tree using grammar " + ": "
# draw_trees(tree)
# http://stackoverflow.com/questions/23429117/saving-nltk-drawn-parse-tree-to-image-file
cf = CanvasFrame()
tc = TreeWidget(cf.canvas(), tree)
cf.add_widget(tc, 10, 10) # (10,10) offsets
# compute the filename from the input, then write the image to the file
filename = 'trees/tree_' + sys.argv[2] + '_' + computeNameFromSentence(lower)
cf.print_to_file(filename + '.ps')
# convert the file to PNG
# http://stackoverflow.com/questions/89228/calling-an-external-command-in-python
call(["convert", filename + '.ps', filename + '.png'])
cf.destroy()
print filename + '.png'
numTrees += 1
示例13: print
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
print(str(e))
# for subtree in namedEnt.subtrees(filter = lambda t: t.label() == 'Chunk'):
# print(subtree)
'''
def extract_entity_names(t):
entity_names = []
if hasattr(t, 'node') and t.node:
if t.node == 'NE':
entity_names.append(' '.join([child[0] for child in t]))
else:
for child in t:
entity_names.extend(extract_entity_names(child))
return entity_names
'''
from nltk import Tree
from nltk.draw.util import CanvasFrame
from nltk.draw import TreeWidget
cf = CanvasFrame()
t = Tree.fromstring('(S (NE this tree))')
tc = TreeWidget(cf.canvas(),t)
cf.add_widget(tc,10,10) # (10,10) offsets
cf.print_to_file('tree.ps')
cf.destroy()
process_content()
示例14: range
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
from nltk.draw import TreeWidget
for auteur in auteurs:
for article in range(10):
# Chargement des fichiers
chemin = './articles_arbres/'+auteur+'/'+str(article)+'.txt'
fichier = open(chemin, 'rb')
A = pickle.load(fichier)
fichier.close()
# Impression des arbres
#A[0].draw()
cf = CanvasFrame()
t = A[0]
tc = TreeWidget(cf.canvas(),t)
cf.add_widget(tc,10,10) # (10,10) offsets
cf.print_to_file('./dessins_arbres/'+auteur+'/'+str(article)+'.ps')
cf.destroy()
示例15: DrtGlueDemo
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import print_to_file [as 别名]
#.........这里部分代码省略.........
if index >= (readingListSize-1):
self._select_next_example()
else:
self._readingList_store_selection(index+1)
else:
#select its first reading
self._readingList_store_selection(0)
else:
self._select_next_example()
def _select_next_example(self):
#if the current example is not the last example
if self._curExample < len(self._examples)-1:
self._exampleList_store_selection(self._curExample+1)
else:
#go to the first example
self._exampleList_store_selection(0)
def about(self, *e):
ABOUT = ("NLTK Discourse Representation Theory (DRT) Glue Semantics Demo\n"+
"Written by Daniel H. Garrette")
TITLE = 'About: NLTK DRT Glue Demo'
try:
from tkMessageBox import Message
Message(message=ABOUT, title=TITLE).show()
except:
ShowText(self._top, TITLE, ABOUT)
def postscript(self, *e):
self._autostep = 0
self._cframe.print_to_file()
def mainloop(self, *args, **kwargs):
"""
Enter the Tkinter mainloop. This function must be called if
this demo is created from a non-interactive program (e.g.
from a secript); otherwise, the demo will close as soon as
the script completes.
"""
if in_idle(): return
self._top.mainloop(*args, **kwargs)
def resize(self, size=None):
if size is not None: self._size.set(size)
size = self._size.get()
self._font.configure(size=-(abs(size)))
self._boldfont.configure(size=-(abs(size)))
self._sysfont.configure(size=-(abs(size)))
self._bigfont.configure(size=-(abs(size+2)))
self._redraw()
def _toggle_remove_duplicates(self):
self._glue.remove_duplicates = not self._glue.remove_duplicates
self._exampleList.selection_clear(0, 'end')
self._readings = []
self._populate_readingListbox()
self._readingCache = [None for ex in self._examples]
self._curExample = -1
self._error = None
self._drs = None
self._redraw()