Convert some string representation of some graph into some networkx graph?
Question:
I am looking for some way to convert some string representation of some directed weighted graph with weights as strings in my case into some networkx graph.
E.g. the string
s = 'graph([p,q,¬p,¬q,p→q,q∧ ¬q],[edge(¬(¬p),¬p∧ ¬(¬p),"∧I"), edge(p,q,"→E"), edge(¬p, ¬p∧ ¬(¬p),"∧I"), edge(¬(¬p),¬p,"¬E"),edge(q,q∧ ¬q,"∧I"),edge(¬q,q∧ ¬q,"∧I"),edge(p→q,q,"→E"),edge(q∧ ¬q,¬p,"¬E"), edge(¬p∧ ¬(¬p),p,"¬E"), edge(¬p,p,"¬E")])'
should lead to something like that:
How can I realize it?
Answers:
Assuming the nodes/edges don’t contain square brackets, you could use regexes:
import networkx as nx
import re
m = re.search(r'^graph([([^]]*)],s*[([^]]*)])$', s)
nodes = m.group(1).split(',')
edges = re.findall(r'edge(([^,]+),([^,]+),([^,]+))', m.group(2))
G = nx.DiGraph()
G.add_nodes_from(nodes)
G.add_edges_from([(u,v,{'label': a.strip('"')}) for u,v,a in edges])
Graph (plotted with graphviz
):
I am looking for some way to convert some string representation of some directed weighted graph with weights as strings in my case into some networkx graph.
E.g. the string
s = 'graph([p,q,¬p,¬q,p→q,q∧ ¬q],[edge(¬(¬p),¬p∧ ¬(¬p),"∧I"), edge(p,q,"→E"), edge(¬p, ¬p∧ ¬(¬p),"∧I"), edge(¬(¬p),¬p,"¬E"),edge(q,q∧ ¬q,"∧I"),edge(¬q,q∧ ¬q,"∧I"),edge(p→q,q,"→E"),edge(q∧ ¬q,¬p,"¬E"), edge(¬p∧ ¬(¬p),p,"¬E"), edge(¬p,p,"¬E")])'
should lead to something like that:
How can I realize it?
Assuming the nodes/edges don’t contain square brackets, you could use regexes:
import networkx as nx
import re
m = re.search(r'^graph([([^]]*)],s*[([^]]*)])$', s)
nodes = m.group(1).split(',')
edges = re.findall(r'edge(([^,]+),([^,]+),([^,]+))', m.group(2))
G = nx.DiGraph()
G.add_nodes_from(nodes)
G.add_edges_from([(u,v,{'label': a.strip('"')}) for u,v,a in edges])
Graph (plotted with graphviz
):