注意
转到末尾下载完整示例代码。
Roget#
构建一个有向图,包含 Roget 词库 1879 年版本中定义的 1022 个类别和 5075 个交叉引用。此示例在以下著作的第 1.2 节中描述:
Donald E. Knuth,《斯坦福图库:组合计算平台》,ACM 出版社,纽约,1993 年。http://www-cs-faculty.stanford.edu/~knuth/sgb.html
注意,5075 个交叉引用中有一个是自环,但它仍包含在此构建的图中,因为标准的 networkx DiGraph
类允许自环。(参见 400pungency:400 401 403 405)。
数据文件位于

skipping self loop 400 400
Loaded roget_dat.txt containing 1022 categories.
DiGraph with 1022 nodes and 5075 edges
21 connected components
import gzip
import re
import sys
import matplotlib.pyplot as plt
import networkx as nx
def roget_graph():
"""Return the thesaurus graph from the roget.dat example in
the Stanford Graph Base.
"""
# open file roget_dat.txt.gz
fh = gzip.open("roget_dat.txt.gz", "r")
G = nx.DiGraph()
for line in fh.readlines():
line = line.decode()
if line.startswith("*"): # skip comments
continue
if line.startswith(" "): # this is a continuation line, append
line = oldline + line
if line.endswith("\\\n"): # continuation line, buffer, goto next
oldline = line.strip("\\\n")
continue
(headname, tails) = line.split(":")
# head
numfind = re.compile(r"^\d+") # re to find the number of this word
head = numfind.findall(headname)[0] # get the number
G.add_node(head)
for tail in tails.split():
if head == tail:
print("skipping self loop", head, tail, file=sys.stderr)
G.add_edge(head, tail)
return G
G = roget_graph()
print("Loaded roget_dat.txt containing 1022 categories.")
print(G)
UG = G.to_undirected()
print(nx.number_connected_components(UG), "connected components")
options = {
"node_color": "black",
"node_size": 1,
"edge_color": "gray",
"linewidths": 0,
"width": 0.1,
}
nx.draw_circular(UG, **options)
plt.show()
脚本总运行时间: (0 分钟 0.203 秒)