networkx
书中代码实现
书中p165,networkx和matplotlib结合使用可视化wordnet的网络结构(语义网络)
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)
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()
if __name__=='__main__':
dog=wn.synset('dog.n.01')
graph=hyponym_graph(dog)
graph_draw(graph)
报错:AttributeError: module ‘networkx’ has no attribute ‘draw_graphviz’
解决方法:
Python3.6版本
nx.draw(graph,node_size=[16 * graph.degree(n) for n in graph], node_color=[graph.depth[n] for n in graph], with_labels=False) 就可以运行了
拓展:wordnet层次图
from nltk.corpus import wordnet as wn
import matplotlib
import networkx as nx
def travers(graph, start, node):
graph.depth[node.name] = node.shortest_path_distance(start)
for child in node.hyponyms():
graph.add_edge(node.name, child.name)
#graph.add_node(child.name, desc=[child])
travers(graph, start, child)
def hyponym_graph(start):
G = nx.Graph()
G.depth = {}
travers(G, start, start)
return G
def graph_draw(graph):
nx.draw(graph, node_size=[5 * graph.degree(n) for n in graph], node_color=[graph.depth[n] for n in graph],
with_labels=True)
matplotlib.pyplot.show()
if __name__=='__main__':
computer = wn.synset('computer.n.01')
graph = hyponym_graph(computer)
graph_draw(graph)
实验结果:
可以显示节点的标签,但是不知道怎么把内容提取出来。待解决。
解决方法
#node.name改为node.name()
from nltk.corpus import wordnet as wn
import matplotlib
import networkx as nx
def travers(graph, start, node):
graph.depth[node.name()] = node.shortest_path_distance(start)
for child in node.hyponyms():
graph.add_edge(node.name(), child.name())
travers(graph, start, child)
def hyponym_graph(start):
G = nx.Graph()
G.depth = {}
travers(G, start, start)
return G
def graph_draw(graph):
nx.draw(graph, node_size=[5 * graph.degree(n) for n in graph], node_color=[graph.depth[n] for n in graph],
with_labels=True)
matplotlib.pyplot.show()
if __name__=='__main__':
computer = wn.synset('computer.n.01')
graph = hyponym_graph(computer)
graph_draw(graph)
书中用函数都没有加(),所以显示出来的都有问题。
例如:
>>> computer.name
<bound method Synset.name of Synset('computer.n.01')>
>>> computer.name()
'computer.n.01'
开心~~~