Created
August 12, 2022 16:08
-
-
Save mommi84/04224360da3680a9c6fc87976d077e22 to your computer and use it in GitHub Desktop.
Visualise NLP dependency trees
This file contains hidden or 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
#!/usr/bin/env python3 | |
# | |
# Requirements: | |
# pip3 install spacy graphviz | |
# python3 -m spacy download en_core_web_lg | |
# | |
import spacy | |
from graphviz import Digraph | |
nlp = spacy.load('en_core_web_lg') | |
class DependencyTree: | |
def __init__(self, text): | |
self.text = text | |
self.dot, self.graph = self.make_tree(text) | |
def make_tree(self, text): | |
dot = Digraph() | |
graph = [] | |
self.doc = nlp(text) | |
for token in self.doc: | |
s, label = str(token.i), f"{token.text} {token.pos_}" | |
dot.node(s, label) | |
graph.append((int(s), 'label', label)) | |
for t in token.children: | |
s, p, o = str(token.i), t.dep_, str(t.i) | |
dot.edge(s, o, label=p) | |
graph.append((int(s), p, int(o))) | |
return dot, graph | |
tree = DependencyTree("Today is very hot, but it's a good day.") | |
# visualise tree in Jupyter | |
tree.dot | |
# export to PNG | |
tree.dot.render('my_tree', format='png', cleanup=True) | |
# list edges | |
tree.graph | |
# spaCy object | |
tree.doc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment