Skip to content

Instantly share code, notes, and snippets.

@andrecunha
Created August 26, 2014 17:55
Show Gist options
  • Save andrecunha/394eb4fc5cc7eea6f873 to your computer and use it in GitHub Desktop.
Save andrecunha/394eb4fc5cc7eea6f873 to your computer and use it in GitHub Desktop.
Convert NLTK dependency graph to Tikz drawing
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