Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

python - String represenation for Graph in networkx

I am looking for a string representation of a Graph from the networkx library. There should be something which lists me all nodes and edges with their attributes. I am new to the library and am convinced there is a simple solution.

Of course I can write an auxiliary function for that, compare graph_to_str in the code example. I am just looking for something more handy, compact and comfortable.

The following code example is based on the official tutorial.

code example

import networkx as nx

G = nx.Graph(day="Friday")
G.add_node(1, time='5pm')
G.add_nodes_from([3], time='2pm', room=714)
G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])

print('What I can get out:')
print('G:', G)
print('G.graph:', G.graph)


def graph_to_str(G):
    txt = 'Graph:'
    txt += '
attributes: ' + str(G.graph)

    txt += '
nodes:'
    for node in G.nodes:
        txt += '
{:} - {:}'.format(str(node), str(G.nodes[node]))

    txt += '
edges:'
    for edge in G.edges:
        txt += '
{:} - {:}'.format(str(edge), str(G.edges[edge]))

    return txt

print()
print('What I am looking for:')
print(graph_to_str(G))

output

What I can get out:
G: 
G.graph: {'day': 'Friday'}

What I am looking for:
Graph:
        attributes: {'day': 'Friday'}
        nodes:
                1 - {'time': '5pm'}
                3 - {'time': '2pm', 'room': 714}
                2 - {}
        edges:
                (1, 2) - {'color': 'blue'}
                (3, 2) - {'weight': 8}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...