本文整理汇总了Python中networkx.utils.is_string_like函数的典型用法代码示例。如果您正苦于以下问题:Python is_string_like函数的具体用法?Python is_string_like怎么用?Python is_string_like使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_string_like函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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
示例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
示例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
示例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")
示例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)
示例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)
示例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
示例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"
示例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
示例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
示例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
示例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
示例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,
)
#.........这里部分代码省略.........