A,B #A is associated to B
A,C #A is associated to C
B,D #B is associated to D
B,E #B is associated to E
C,F #C is associated to F
C,G #C is associated to G
parent = {}
children = {}
with open( 'my.csv', 'rt' ) as fh:
for line in fh:
# strip the comments and line endings
if '#' in line: line = line[ :line.index( '#' ) ]
line = line.strip()
if line:
# record the association
node, subnode = line.split( ',', 1 )
parent[ subnode ] = node
children.setdefault( node, [] ).append( subnode )
import networkx as nx
import matplotlib.pyplot as plt
text =\
"""A,B
A,C
B,D
B,E
C,F
C,G"""
graph = nx.DiGraph()
for i in text.split('\n'):
graph.add_edge(i[0], i[2])
nx.draw(graph, with_labels=True)
plt.show()
假设文件
my.csv
包含您给出的示例输入,此代码将图形结构记录在两个简单的Pythondict
对象中:语法
children['A']
允许您查找属于节点'A'
的子节点列表,语法parent['B']
允许您以另一种方式查找节点'B'
的父节点。或者你也可以用以下方式打印整个内容:输出:
使用networkx生成有向图,matplotlib绘制有向图的图像:
注意这一行:
graph.add_edge(i[0], i[2])
如果此图中不存在该节点,则会自动创建该节点。你知道吗绘图:
保存信息的一种自然结构是一个字典,其中每个条目的键是一个节点名(例如,C),它出现在csv文件中的一行左侧,而dict条目的值是一个数组,它最终包含作为该键直接子项的所有节点的名称(例如,[F,G])。你知道吗
因此,在处理csv文件的每一行(如B,D)时,请检查第一个元素(如B)是否已经是dict中的键。如果不是,请在dict中添加一个key=B和value=D的条目。如果已经存在,则将第二个元素附加到该键的数组值。例如,当您到达数据行B,E时,您将找到B的条目(B=>;[D]),并将E附加到其值上,得到[D,E]。你知道吗
完成后,如果某个节点的名称从未出现在任何条目的数组值中,则该节点就是树的根。如果有多个节点具有此属性,则这些节点中的每个节点都是树林中树的根。你知道吗
相关问题 更多 >
编程相关推荐