本文整理汇总了Python中networkx.utils.is_string_like函数的典型用法代码示例。如果您正苦于以下问题:Python is_string_like函数的具体用法?Python is_string_like怎么用?Python is_string_like使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_string_like函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: generate_pajek_
def generate_pajek_(G):
import warnings
from networkx.utils import is_string_like, open_file, make_str
if G.name == '':
name = 'NetworkX'
else:
name = G.name
# Apparently many Pajek format readers can't process this line
# So we'll leave it out for now.
# yield '*network %s'%name
# write nodes with attributes
yield '*vertices %s' % (G.order())
nodes = list(G)
# make dictionary mapping nodes to integers
nodenumber = dict(zip(nodes, range(1, len(nodes) + 1)))
for n in nodes:
# copy node attributes and pop mandatory attributes
# to avoid duplication.
na = G.nodes.get(n, {}).copy()
x = na.pop('x', 0.0)
y = na.pop('y', 0.0)
id = int(na.pop('id', nodenumber[n]))
nodenumber[n] = id
shape = na.pop('shape', 'ellipse')
s = ' '.join(map(make_qstr, (id, n, x, y, shape)))
# only optional attributes are left in na.
for k, v in na.items():
if is_string_like(v) and v.strip() != '':
s += ' %s %s' % (make_qstr(k), make_qstr(v))
else:
warnings.warn('Node attribute %s is not processed. %s.' %
(k,
'Empty attribute' if is_string_like(v) else
'Non-string attribute'))
s = s.replace('\n', ' ')
yield s
# write edges with attributes
if G.is_directed():
yield '*arcs'
else:
yield '*edges'
for u, v, edgedata in G.edges(data=True):
d = edgedata.copy()
value = d.pop('weight', 1.0) # use 1 as default edge value
s = ' '.join(map(make_qstr, (nodenumber[u], nodenumber[v], value)))
for k, v in d.items():
if is_string_like(v) and v.strip() != '':
s += ' %s %s' % (make_qstr(k), make_qstr(v))
s += ' '
else:
warnings.warn('Edge attribute %s is not processed. %s.' %
(k,
'Empty attribute' if is_string_like(v) else
'Non-string attribute'))
yield s
开发者ID:haobruce,项目名称:CUNY,代码行数:58,代码来源:networkx_util.py
示例2: generate_pajek
def generate_pajek(G):
"""Generate lines in Pajek graph format.
Parameters
----------
G : graph
A Networkx graph
References
----------
See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
for format information.
"""
if G.name=='':
name='NetworkX'
else:
name=G.name
yield '*network %s'%name
# write nodes with attributes
yield '*vertices %s'%(G.order())
nodes = G.nodes()
# make dictionary mapping nodes to integers
nodenumber=dict(zip(nodes,range(1,len(nodes)+1)))
for n in nodes:
na=G.node.get(n,{})
x=na.get('x',0.0)
y=na.get('y',0.0)
id=int(na.get('id',nodenumber[n]))
nodenumber[n]=id
shape=na.get('shape','ellipse')
s=' '.join(map(make_str,(id,n,x,y,shape)))
for k,v in na.items():
if is_string_like(v):
# add quotes to any values with a blank space
if " " in v:
v="\"%s\""%v
s+=' %s %s'%(k,v)
yield s
# write edges with attributes
if G.is_directed():
yield '*arcs'
else:
yield '*edges'
for u,v,edgedata in G.edges(data=True):
d=edgedata.copy()
value=d.pop('weight',1.0) # use 1 as default edge value
s=' '.join(map(make_str,(nodenumber[u],nodenumber[v],value)))
for k,v in d.items():
if is_string_like(v):
# add quotes to any values with a blank space
if " " in v:
v="\"%s\""%v
s+=' %s %s'%(k,v)
yield s
开发者ID:adrianco,项目名称:networkx,代码行数:56,代码来源:pajek.py
示例3: parse_p2g
def parse_p2g(lines):
"""Parse p2g format graph from string or iterable.
Returns an MultiDiGraph.
"""
if is_string_like(lines): lines=iter(lines.split('\n'))
lines = iter([line.rstrip('\n') for line in lines])
description = lines.next()
# are multiedges (parallel edges) allowed?
G=networkx.MultiDiGraph(name=description,selfloops=True)
nnodes,nedges=map(int,lines.next().split())
nodelabel={}
nbrs={}
# loop over the nodes keeping track of node labels and out neighbors
# defer adding edges until all node labels are known
for i in range(nnodes):
n=lines.next()
nodelabel[i]=n
G.add_node(n)
nbrs[n]=map(int,lines.next().split())
# now we know all of the node labels so we can add the edges
# with the correct labels
for n in G:
for nbr in nbrs[n]:
G.add_edge(n,nodelabel[nbr])
return G
开发者ID:Bludge0n,项目名称:AREsoft,代码行数:29,代码来源:p2g.py
示例4: add_prefix1
def add_prefix1(x):
prefix = rename[1]
if is_string_like(x):
name = prefix + x
else:
name = prefix + repr(x)
return name
开发者ID:bjedwards,项目名称:NetworkX_fork,代码行数:7,代码来源:operators.py
示例5: make_qstr
def make_qstr(t):
"""Return the string representation of t.
Add outer double-quotes if the string has a space.
"""
if not is_string_like(t):
t = str(t)
if " " in t:
t=r'"%s"'%t
return t
开发者ID:Bramas,项目名称:networkx,代码行数:9,代码来源:pajek.py
示例6: write_pajek
def write_pajek(G, path):
"""Write in Pajek format to path.
Parameters
----------
G : graph
A networkx graph
path : file or string
File or filename to write.
Filenames ending in .gz or .bz2 will be compressed.
Examples
--------
>>> G=nx.path_graph(4)
>>> nx.write_pajek(G, "test.net")
"""
fh=_get_fh(path,mode='w')
if G.name=='':
name="NetworkX"
else:
name=G.name
fh.write("*network %s\n"%name)
# write nodes with attributes
fh.write("*vertices %s\n"%(G.order()))
nodes = G.nodes()
# make dictionary mapping nodes to integers
nodenumber=dict(zip(nodes,range(1,len(nodes)+1)))
for n in nodes:
na=G.node[n].copy()
x=na.pop('x',0.0)
y=na.pop('y',0.0)
id=int(na.pop('id',nodenumber[n]))
nodenumber[n]=id
shape=na.pop('shape','ellipse')
fh.write("%d \"%s\" %f %f %s "%(id,n,float(x),float(y),shape))
for k,v in na.items():
fh.write("%s %s "%(k,v))
fh.write("\n")
# write edges with attributes
if G.is_directed():
fh.write("*arcs\n")
else:
fh.write("*edges\n")
for u,v,edgedata in G.edges(data=True):
d=edgedata.copy()
value=d.pop('weight',1.0) # use 1 as default edge value
fh.write("%d %d %f "%(nodenumber[u],nodenumber[v],float(value)))
for k,v in d.items():
if is_string_like(v):
# add quotes to any values with a blank space
if " " in v:
v="\"%s\""%v
fh.write("%s %s "%(k,v))
fh.write("\n")
开发者ID:mhawthorne,项目名称:antonym,代码行数:57,代码来源:pajek.py
示例7: string_item
def string_item(k,v,indent):
# try to make a string of the data
if type(v)==dict:
v=listify(v,indent,2)
elif is_string_like(v):
v='"%s"'%v
elif type(v)==bool:
v=int(v)
return "%s %s"%(k,v)
开发者ID:NikitaVAP,项目名称:pycdb,代码行数:9,代码来源:gml.py
示例8: string_item
def string_item(k,v,indent):
# try to make a string of the data
if type(v) == dict:
v = listify(v, indent, 2)
elif is_string_like(v):
v = '"{0}"'.format(escape(v, quote=True))
#v = '"{0}"'.format(v, quote=True)
elif type(v) == bool:
v = int(v)
return "{0} {1}".format(k,v)
开发者ID:ktalik,项目名称:mining-social-network-graphs,代码行数:10,代码来源:readwrite_gml.py
示例9: parse_leda
def parse_leda(lines):
"""Read graph in LEDA format from string or iterable.
Parameters
----------
lines : string or iterable
Data in LEDA format.
Returns
-------
G : NetworkX graph
Examples
--------
G=nx.parse_leda(string)
References
----------
.. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
"""
if is_string_like(lines):
lines = iter(lines.split('\n'))
lines = iter([line.rstrip('\n') for line in lines
if not (line.startswith('#') or line.startswith('\n') or line == '')])
for i in range(3):
next(lines)
# Graph
du = int(next(lines)) # -1=directed, -2=undirected
if du == -1:
G = nx.DiGraph()
else:
G = nx.Graph()
# Nodes
n = int(next(lines)) # number of nodes
node = {}
for i in range(1, n + 1): # LEDA counts from 1 to n
symbol = next(lines).rstrip().strip('|{}| ')
if symbol == "":
symbol = str(i) # use int if no label - could be trouble
node[i] = symbol
G.add_nodes_from([s for i, s in node.items()])
# Edges
m = int(next(lines)) # number of edges
for i in range(m):
try:
s, t, reversal, label = next(lines).split()
except:
raise NetworkXError('Too few fields in LEDA.GRAPH edge %d' % (i + 1))
# BEWARE: no handling of reversal edges
G.add_edge(node[int(s)], node[int(t)], label=label[2:-2])
return G
开发者ID:aparamon,项目名称:networkx,代码行数:54,代码来源:leda.py
示例10: graphml_datatype
def graphml_datatype(val):
if val is None:
return "string"
if is_string_like(val):
return "string"
if type(val) == type(1):
return "int"
if type(val) == type(1.0):
return "double"
if type(val) == type(True):
return "boolean"
if type(val) == type(1L):
return "long"
开发者ID:JaneliaSciComp,项目名称:Neuroptikon,代码行数:13,代码来源:graphml.py
示例11: parse_pajek
def parse_pajek(lines):
"""Parse pajek format graph from string or iterable.."""
import shlex
if is_string_like(lines): lines=iter(lines.split('\n'))
lines = iter([line.rstrip('\n') for line in lines])
G=networkx.XDiGraph(selfloops=True) # are multiedges allowed in Pajek?
G.node_attr={} # dictionary to hold node attributes
directed=True # assume this is a directed network for now
while lines:
try:
l=lines.next()
except: #EOF
break
if l.startswith("*network"):
label,name=l.split()
G.name=name
if l.startswith("*vertices"):
nodelabels={}
l,nnodes=l.split()
for i in range(int(nnodes)):
splitline=shlex.split(lines.next())
id,label,x,y,shape=splitline[0:5]
G.add_node(label)
nodelabels[id]=label
G.node_attr[label]={'id':id,'x':x,'y':y,'shape':shape}
extra_attr=zip(splitline[5::2],splitline[6::2])
G.node_attr[label].update(extra_attr)
if l.startswith("*edges") or l.startswith("*arcs"):
if l.startswith("*edge"):
G=networkx.XGraph(G) # switch from digraph to graph
for l in lines:
splitline=shlex.split(l)
ui,vi,w=splitline[0:3]
u=nodelabels.get(ui,ui)
v=nodelabels.get(vi,vi)
edge_data={'value':float(w)}
extra_attr=zip(splitline[3::2],splitline[4::2])
edge_data.update(extra_attr)
G.add_edge(u,v,edge_data)
return G
开发者ID:conerade67,项目名称:biana,代码行数:40,代码来源:pajek.py
示例12: parse_leda
def parse_leda(lines):
"""Parse LEDA.GRAPH format from string or iterable.
Returns an Graph or DiGraph."""
if is_string_like(lines): lines=iter(lines.split('\n'))
lines = iter([line.rstrip('\n') for line in lines \
if not (line.startswith('#') or line.startswith('\n') or line=='')])
for i in range(3):
lines.next()
# Graph
du = int(lines.next()) # -1 directed, -2 undirected
if du==-1:
G = networkx.DiGraph()
else:
G = networkx.Graph()
# Nodes
n =int(lines.next()) # number of vertices
node={}
for i in range(1,n+1): # LEDA counts from 1 to n
symbol=lines.next()[2:-3] # strip out data from |{data}|
if symbol=="": symbol=str(i) # use int if no label - could be trouble
node[i]=symbol
G.add_nodes_from([s for i,s in node.items()])
# Edges
m = int(lines.next()) # number of edges
for i in range(m):
try:
s,t,reversal,label=lines.next().split()
except:
raise NetworkXError,\
'Too few fields in LEDA.GRAPH edge %d' % (i+1)
# BEWARE: no handling of reversal edges
G.add_edge(node[int(s)],node[int(t)],label=label[2:-2])
return G
开发者ID:jbjorne,项目名称:CVSTransferTest,代码行数:36,代码来源:leda.py
示例13: parse_pajek
def parse_pajek(lines,edge_attr=True):
"""Parse pajek format graph from string or iterable.
Primarily used as a helper for read_pajek().
See Also
--------
read_pajek()
"""
import shlex
if is_string_like(lines): lines=iter(lines.split('\n'))
lines = iter([line.rstrip('\n') for line in lines])
G=nx.MultiDiGraph() # are multiedges allowed in Pajek?
directed=True # assume this is a directed network for now
while lines:
try:
l=lines.next()
except: #EOF
break
if l.lower().startswith("*network"):
label,name=l.split()
G.name=name
if l.lower().startswith("*vertices"):
nodelabels={}
l,nnodes=l.split()
for i in range(int(nnodes)):
splitline=shlex.split(lines.next())
id,label=splitline[0:2]
G.add_node(label)
nodelabels[id]=label
G.node[label]={'id':id}
try:
x,y,shape=splitline[2:5]
G.node[label].update({'x':x,'y':y,'shape':shape})
except:
pass
extra_attr=zip(splitline[5::2],splitline[6::2])
G.node[label].update(extra_attr)
if l.lower().startswith("*edges") or l.lower().startswith("*arcs"):
if l.lower().startswith("*edge"):
# switch from digraph to graph
G=nx.MultiGraph(G)
for l in lines:
splitline=shlex.split(l)
ui,vi=splitline[0:2]
u=nodelabels.get(ui,ui)
v=nodelabels.get(vi,vi)
# parse the data attached to this edge and
# put it in a dictionary
edge_data={}
try:
# there should always be a single value on the edge?
w=splitline[2:3]
edge_data.update({'weight':float(w[0])})
except:
pass
# if there isn't, just assign a 1
# edge_data.update({'value':1})
extra_attr=zip(splitline[3::2],splitline[4::2])
edge_data.update(extra_attr)
G.add_edge(u,v,**edge_data)
return G
开发者ID:mhawthorne,项目名称:antonym,代码行数:64,代码来源:pajek.py
示例14: draw_networkx_edge_labels
#.........这里部分代码省略.........
font_weight : string
Font weight (default='normal')
font_family : string
Font family (default='sans-serif')
bbox : Matplotlib bbox
Specify text box shape and colors.
clip_on : bool
Turn on clipping at axis boundaries (default=True)
Returns
-------
dict
`dict` of labels keyed on the edges
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
Also see the NetworkX drawing examples at
https://networkx.github.io/documentation/latest/auto_examples/index.html
See Also
--------
draw()
draw_networkx()
draw_networkx_nodes()
draw_networkx_edges()
draw_networkx_labels()
"""
try:
import matplotlib.pyplot as plt
import matplotlib.cbook as cb
import numpy as np
except ImportError:
raise ImportError("Matplotlib required for draw()")
except RuntimeError:
print("Matplotlib unable to open display")
raise
if ax is None:
ax = plt.gca()
if edge_labels is None:
labels = {(u, v): d for u, v, d in G.edges(data=True)}
else:
labels = edge_labels
text_items = {}
for (n1, n2), label in labels.items():
(x1, y1) = pos[n1]
(x2, y2) = pos[n2]
(x, y) = (x1 * label_pos + x2 * (1.0 - label_pos),
y1 * label_pos + y2 * (1.0 - label_pos))
if rotate:
angle = np.arctan2(y2 - y1, x2 - x1) / (2.0 * np.pi) * 360 # degrees
# make label orientation "right-side-up"
if angle > 90:
angle -= 180
if angle < - 90:
angle += 180
# transform data coordinate angle to screen coordinate angle
xy = np.array((x, y))
trans_angle = ax.transData.transform_angles(np.array((angle,)),
xy.reshape((1, 2)))[0]
else:
trans_angle = 0.0
# use default box of white with white border
if bbox is None:
bbox = dict(boxstyle='round',
ec=(1.0, 1.0, 1.0),
fc=(1.0, 1.0, 1.0),
)
if not is_string_like(label):
label = str(label) # this will cause "1" and 1 to be labeled the same
# set optional alignment
horizontalalignment = kwds.get('horizontalalignment', 'center')
verticalalignment = kwds.get('verticalalignment', 'center')
t = ax.text(x, y,
label,
size=font_size,
color=font_color,
family=font_family,
weight=font_weight,
alpha=alpha,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
rotation=trans_angle,
transform=ax.transData,
bbox=bbox,
zorder=1,
clip_on=True,
)
text_items[(n1, n2)] = t
return text_items
开发者ID:aparamon,项目名称:networkx,代码行数:101,代码来源:nx_pylab.py
示例15: draw_networkx_labels
def draw_networkx_labels(G, pos,
labels=None,
font_size=12,
font_color='k',
font_family='sans-serif',
font_weight='normal',
alpha=1.0,
bbox=None,
ax=None,
**kwds):
"""Draw node labels on the graph G.
Parameters
----------
G : graph
A networkx graph
pos : dictionary
A dictionary with nodes as keys and positions as values.
Positions should be sequences of length 2.
labels : dictionary, optional (default=None)
Node labels in a dictionary keyed by node of text labels
font_size : int
Font size for text labels (default=12)
font_color : string
Font color string (default='k' black)
font_family : string
Font family (default='sans-serif')
font_weight : string
Font weight (default='normal')
alpha : float
The text transparency (default=1.0)
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
Returns
-------
dict
`dict` of labels keyed on the nodes
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
Also see the NetworkX drawing examples at
https://networkx.github.io/documentation/latest/auto_examples/index.html
See Also
--------
draw()
draw_networkx()
draw_networkx_nodes()
draw_networkx_edges()
draw_networkx_edge_labels()
"""
try:
import matplotlib.pyplot as plt
import matplotlib.cbook as cb
except ImportError:
raise ImportError("Matplotlib required for draw()")
except RuntimeError:
print("Matplotlib unable to open display")
raise
if ax is None:
ax = plt.gca()
if labels is None:
labels = dict((n, n) for n in G.nodes())
# set optional alignment
horizontalalignment = kwds.get('horizontalalignment', 'center')
verticalalignment = kwds.get('verticalalignment', 'center')
text_items = {} # there is no text collection so we'll fake one
for n, label in labels.items():
(x, y) = pos[n]
if not is_string_like(label):
label = str(label) # this will cause "1" and 1 to be labeled the same
t = ax.text(x, y,
label,
size=font_size,
color=font_color,
family=font_family,
weight=font_weight,
alpha=alpha,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
transform=ax.transData,
bbox=bbox,
clip_on=True,
)
#.........这里部分代码省略.........
开发者ID:aparamon,项目名称:networkx,代码行数:101,代码来源:nx_pylab.py
示例16: draw_networkx_edges
#.........这里部分代码省略.........
draw_networkx_labels()
draw_networkx_edge_labels()
"""
try:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cbook as cb
from matplotlib.colors import colorConverter, Colormap
from matplotlib.collections import LineCollection
import numpy as np
except ImportError:
raise ImportError("Matplotlib required for draw()")
except RuntimeError:
print("Matplotlib unable to open display")
raise
if ax is None:
ax = plt.gca()
if edgelist is None:
edgelist = list(G.edges())
if not edgelist or len(edgelist) == 0: # no edges!
return None
# set edge positions
edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
if not cb.iterable(width):
lw = (width,)
else:
lw = width
if not is_string_like(edge_color) \
and cb.iterable(edge_color) \
and len(edge_color) == len(edge_pos):
if np.alltrue([is_string_like(c) for c in edge_color]):
# (should check ALL elements)
# list of color letters such as ['k','r','k',...]
edge_colors = tuple([colorConverter.to_rgba(c, alpha)
for c in edge_color])
elif np.alltrue([not is_string_like(c) for c in edge_color]):
# If color specs are given as (rgb) or (rgba) tuples, we're OK
if np.alltrue([cb.iterable(c) and len(c) in (3, 4)
for c in edge_color]):
edge_colors = tuple(edge_color)
else:
# numbers (which are going to be mapped with a colormap)
edge_colors = None
else:
raise ValueError('edge_color must consist of either color names or numbers')
else:
if is_string_like(edge_color) or len(edge_color) == 1:
edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
else:
raise ValueError(
'edge_color must be a single color or list of exactly m colors where m is the number or edges')
edge_collection = LineCollection(edge_pos,
colors=edge_colors,
linewidths=lw,
antialiaseds=(1,),
linestyle=style,
transOffset=ax.transData,
)
开发者ID:aparamon,项目名称:networkx,代码行数:66,代码来源:nx_pylab.py
示例17: label
def label(x):
if is_string_like(x):
name = prefix + x
else:
name = prefix + repr(x)
return name
开发者ID:networkx,项目名称:networkx,代码行数:6,代码来源:binary.py
示例18: type
else:
node_attr={}
indent=2*' '
count=iter(range(len(G)))
node_id={}
yield "graph ["
if G.is_directed():
yield indent+"directed 1"
# write graph attributes
for k,v in G.graph.items():
<<<<<<< local
if type(v)==dicttype:
v=listify(v,indent,2)
elif is_string_like(v):
v='"%s"'%v
elif type(v) == bool:
v = int(v)
yield indent+"%s %s"%(k,v)
=======
yield indent+string_item(k,v,indent)
>>>>>>> other
# write nodes
for n in G:
yield indent+"node ["
# get id or assign number
nid=G.node[n].get('id',next(count))
node_id[n]=nid
yield 2*indent+"id %s"%nid
label=G.node[n].pop('label',n)
开发者ID:sk2,项目名称:topzootools,代码行数:31,代码来源:gml_custom.py
示例19: parse_pajek
def parse_pajek(lines):
"""Parse pajek format graph from string or iterable.."""
import shlex
if is_string_like(lines): lines=iter(lines.split('\n'))
lines = iter([line.rstrip('\n') for line in lines])
G=networkx.DiGraph() # are multiedges allowed in Pajek?
G.node_attr={} # dictionary to hold node attributes
directed=True # assume this is a directed network for now
while lines:
try:
l=lines.next()
l=l.lower()
except: #EOF
break
if l.startswith("#"):
continue
if l.startswith("*network"):
label,name=l.split()
G.name=name
if l.startswith("*vertices"):
nodelabels={}
l,nnodes=l.split()
while not l.startswith("*arcs"):
if l.startswith('#'):
l = lines.next()
l = l.lower()
continue
if l.startswith('*'):
l = lines.next()
l = l.lower()
continue
splitline=shlex.split(l)
#print splitline
id, label = splitline[0:2]
G.add_node(label)
nodelabels[id]=label
G.node_attr[label]={'id':id}
if len(splitline) > 2:
id,label,x,y=splitline[0:4]
G.node_attr[label]={'id':id,'x':x,'y':y}
extra_attr=zip(splitline[4::2],splitline[5::2])
#print extra_attr
G.node_attr[label].update(extra_attr)
l = lines.next()
l = l.lower()
if l.startswith("*arcs"):
for l in lines:
if not l: break
if l.startswith('#'): continue
splitline=shlex.split(l)
ui,vi,w=splitline[0:3]
u=nodelabels.get(ui,ui)
v=nodelabels.get(vi,vi)
edge_data={'value':float(w)}
extra_attr=zip(splitline[3::2],splitline[4::2])
edge_data.update(extra_attr)
if G.has_edge(u,v):
if G[u][v]['value'] > float(w):
G.add_edge(u,v,**edge_data)
else:
G.add_edge(u,v,**edge_data)
if not G.name:
raise Exception("No graph definition found")
if len(G.nodes()) == 0:
raise Exception("No graph definition found")
return G
开发者ID:UNINETT,项目名称:PyMetric,代码行数:66,代码来源:pajek.py
示例20: parse_pajek
def parse_pajek(lines):
"""Parse Pajek format graph from string or iterable.
Parameters
----------
lines : string or iterable
Data in Pajek format.
Returns
-------
G : NetworkX graph
See Also
--------
read_pajek()
"""
import shlex
# multigraph=False
if is_string_like(lines): lines=iter(lines.split('\n'))
lines = iter([line.rstrip('\n') for line in lines])
G=nx.MultiDiGraph() # are multiedges allowed in Pajek? assume yes
while lines:
try:
l=next(lines)
except: #EOF
break
if l.lower().startswith("*network"):
try:
label, name = l.split()
except ValueError:
# Line was not of the form: *network NAME
pass
else:
G.graph['name'] = name
elif l.lower().startswith("*vertices"):
nodelabels={}
l,nnodes=l.split()
for i in range(int(nnodes)):
splitline=shlex.split(str(next(lines)))
id,label=splitline[0:2]
G.add_node(label)
nodelabels[id]=label
G.node[label]={'id':id}
try:
x,y,shape=splitline[2:5]
G.node[label].update({'x':float(x),
'y':float(y),
'shape':shape})
except:
pass
extra_attr=zip(splitline[5::2],splitline[6::2])
G.node[label].update(extra_attr)
elif l.lower().startswith("*edges") or l.lower().startswith("*arcs"):
if l.lower().startswith("*edge"):
# switch from multidigraph to multigraph
G=nx.MultiGraph(G)
if l.lower().startswith("*arcs"):
# switch to directed with multiple arcs for each existing edge
G=G.to_directed()
for l in lines:
splitline=shlex.split(str(l))
if len(splitline)<2:
continue
ui,vi=splitline[0:2]
u=nodelabels.get(ui,ui)
v=nodelabels.get(vi,vi)
# parse the data attached to this edge and put in a dictionary
edge_data={}
try:
# there should always be a single value on the edge?
w=splitline[2:3]
edge_data.update({'weight':float(w[0])})
except:
pass
# if there isn't, just assign a 1
# edge_data.update({'value':1})
extra_attr=zip(splitline[3::2],splitline[4::2])
edge_data.update(extra_attr)
# if G.has_edge(u,v):
# multigraph=True
G.add_edge(u,v,**edge_data)
return G
开发者ID:Bramas,项目名称:networkx,代码行数:83,代码来源:pajek.py
注:本文中的networkx.utils.is_string_like函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论