Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...