1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#!/usr/bin/python3
import networkx as nx
import sys
sys.path.append("/usr/share/botch")
from util import read_graph, find_nodes
class format_dict(dict):
def __missing__(self, key):
return "{" + key + "}"
def graph2text(g, fmt, vertices):
if vertices:
nodes = find_nodes(g, vertices)
else:
nodes = nx.nodes(g)
for n in nodes:
fdict = format_dict(g.nodes[n])
fdict["__ID__"] = n
print(fmt.format(**fdict))
return True
def vertex(string):
try:
key, value = string.split(":", 1)
except ValueError:
raise argparse.ArgumentTypeError("key must be separated from value by a colon")
return key, value
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description='Given a format string of the form "{attr1} {attr2}", '
"print a line with this format for every vertex in the "
"graph, replacing {attr} placeholders with the value of "
'the attribute "attr" for that vertex. The special '
"placeholder {__ID__} is replaced with the vertex "
"identifier."
)
parser.add_argument(
"g",
type=read_graph,
nargs="?",
default="-",
help="Input graph in GraphML or dot format (default: " "stdin)",
)
parser.add_argument(
"formatstring",
type=str,
help="All occurences of the "
"form {XXX} in the format string, will be replaced by "
'the vertex attribute with name "XXX". If no '
'attribute with name "XXX" was found, then the '
"placeholder {XXX} remains in the output string. To "
"write a literal opening or closing curly brace, type "
"them twice, respectively.",
)
parser.add_argument(
"--vertex",
type=vertex,
action="append",
help="key:value pairs to match the vertices to output",
)
parser.add_argument("-v", "--verbose", action="store_true", help="be verbose")
args = parser.parse_args()
ret = graph2text(args.g, args.formatstring, args.vertex)
exit(not ret)
|