The NetworkX package is for defining and manipulating structures consisting of nodes and edges, known as graphs. It is available from https://networkx.lanl.gov/. NetworkX

f 1 press: reportage {■I religion IB skill and hobbies i I miscellaneous: gov fiction: adventure

Figure 4-4. Bar chart showing frequency of modals in different sections of Brown Corpus: This visualization was produced by the program in Example 4-10.

can be used in conjunction with Matplotlib to visualize networks, such as WordNet (the semantic network we introduced in Section 2.5). The program in Example 4-11 initializes an empty graph © and then traverses the WordNet hypernym hierarchy adding edges to the graph O. Notice that the traversal is recursive ©, applying the programming technique discussed in Section 4.7. The resulting display is shown in Figure 4-5.

Example 4-11. Using the NetworkX and Matplotlib libraries.

import networkx as nx import matplotlib from nltk.corpus import wordnet as wn def traverse(graph, start, node):

graph.depth[node.name] = node.shortest_path_distance(start) for child in node.hyponyms():

graph.add_edge(node.name, child.name) O traverse(graph, start, child) ©

def hyponym_graph(start): G = nx.Graph() © G.depth = {}

traverse(G, start, start) return G

def graph_draw(graph):

nx.draw_graphviz(graph, node_size = [16 * graph.degree(n) for n in graph], node_color = [graph.depth[n] for n in graph], with_labels = False) matplotlib.pyplot.show()

>>> dog = wn.synset('dog.n.Ol') >>> graph = hyponym_graph(dog) >>> graph_draw(graph)

Was this article helpful?

## Post a comment