Created
August 26, 2014 17:55
-
-
Save andrecunha/394eb4fc5cc7eea6f873 to your computer and use it in GitHub Desktop.
Convert NLTK dependency graph to Tikz drawing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def as_tikz_graph(graph): | |
"""Converts an nltk.parse.dependencygraph.DependencyGraph object to a Tikz | |
drawing. | |
:graph: An NLTK dependency graph. | |
:returns: A string containing the LaTeX code to draw the graph with the | |
tikz-dependency package. | |
""" | |
nodes = graph.nodelist | |
template = """\\begin{{dependency}} | |
\\begin{{deptext}}[column sep=0.5cm] | |
{deptext} | |
\\end{{deptext}} | |
{depedges} | |
\\end{{dependency}}""" | |
deptext = ' \\& '.join([node['word'] for node in nodes | |
if node['word'] is not None]) + ' \\\\' | |
edge_template = '\\depedge{{{origin}}}{{{dest}}}{{{rel}}}' | |
root_node_template = '\\deproot{{{dest}}}{{root}}' | |
def edge_as_string(node): | |
if node['rel'] == 'null': | |
return root_node_template.format(dest=node['address']) | |
return edge_template.format(origin=node['head'], | |
dest=node['address'], | |
rel=node['rel']) | |
depedges = '\n'.join([' ' + edge_as_string(edge) for edge in nodes | |
if edge['rel'] != 'TOP']) | |
return template.format(deptext=deptext, depedges=depedges) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment