summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorloicseguin <none@none>2010-08-07 04:35:01 +0000
committerloicseguin <none@none>2010-08-07 04:35:01 +0000
commit4a1aa2f7c0a8d19b0dbc69ebc59f02ba696e77ab (patch)
treee8310edc3d82876665b73c9695c31ffb08923053 /examples
parent9c994bd9a032d60e2a437d4e7084abe867f056ea (diff)
downloadnetworkx-4a1aa2f7c0a8d19b0dbc69ebc59f02ba696e77ab.tar.gz
Ported examples/graph for Python 3. Refs #384
--HG-- extra : convert_revision : svn%3A3ed01bd8-26fb-0310-9e4c-ca1a4053419f/networkx/trunk%401856
Diffstat (limited to 'examples')
-rw-r--r--examples/graph/atlas.py6
-rw-r--r--examples/graph/atlas2.py4
-rw-r--r--examples/graph/degree_sequence.py14
-rw-r--r--examples/graph/erdos_renyi.py9
-rw-r--r--examples/graph/expected_degree_sequence.py6
-rw-r--r--examples/graph/football.py19
-rw-r--r--examples/graph/karate_club.py8
-rw-r--r--examples/graph/knuth_miles.py14
-rw-r--r--examples/graph/napoleon_russian_campaign.py41
-rw-r--r--examples/graph/roget.py19
-rwxr-xr-xexamples/graph/unix_email.py11
-rw-r--r--examples/graph/words.py32
12 files changed, 93 insertions, 90 deletions
diff --git a/examples/graph/atlas.py b/examples/graph/atlas.py
index 73231c3a..7aca6cb8 100644
--- a/examples/graph/atlas.py
+++ b/examples/graph/atlas.py
@@ -58,9 +58,9 @@ if __name__ == '__main__':
G=atlas6()
- print "graph has %d nodes with %d edges"\
- %(nx.number_of_nodes(G),nx.number_of_edges(G))
- print nx.number_connected_components(G),"connected components"
+ print("graph has %d nodes with %d edges"\
+ %(nx.number_of_nodes(G),nx.number_of_edges(G)))
+ print(nx.number_connected_components(G),"connected components")
try:
diff --git a/examples/graph/atlas2.py b/examples/graph/atlas2.py
index bae417a3..1c68540a 100644
--- a/examples/graph/atlas2.py
+++ b/examples/graph/atlas2.py
@@ -23,8 +23,8 @@ atlas=graph_atlas_g()[0:20]
for G in atlas:
- print "graph %s has %d nodes with %d edges"\
- %(G.name,NX.number_of_nodes(G),NX.number_of_edges(G))
+ print("graph %s has %d nodes with %d edges"
+ %(G.name,NX.number_of_nodes(G),NX.number_of_edges(G)))
A=NX.to_agraph(G)
A.graph_attr['label']=G.name
# set default node attributes
diff --git a/examples/graph/degree_sequence.py b/examples/graph/degree_sequence.py
index 1c7cb208..e4694ed8 100644
--- a/examples/graph/degree_sequence.py
+++ b/examples/graph/degree_sequence.py
@@ -19,19 +19,19 @@ from networkx.generators.degree_seq import *
z=[5,3,3,3,3,2,2,2,1,1,1]
is_valid_degree_sequence(z)
-print "Configuration model"
+print("Configuration model")
G=configuration_model(z) # configuration model
-degree_sequence=degree(G).values() # degree sequence
-print "Degree sequence", degree_sequence
-print "Degree histogram"
+degree_sequence=list(degree(G).values()) # degree sequence
+print("Degree sequence %s" % degree_sequence)
+print("Degree histogram")
hist={}
for d in degree_sequence:
- if hist.has_key(d):
+ if d in hist:
hist[d]+=1
else:
hist[d]=1
-print "degree #nodes"
+print("degree #nodes")
for d in hist:
- print d,hist[d]
+ print('%d %d' % (d,hist[d]))
diff --git a/examples/graph/erdos_renyi.py b/examples/graph/erdos_renyi.py
index da46f95c..3ac9f7ea 100644
--- a/examples/graph/erdos_renyi.py
+++ b/examples/graph/erdos_renyi.py
@@ -26,10 +26,13 @@ m=20 # 20 edges
G=gnm_random_graph(n,m)
# some properties
-print "node degree clustering"
+print("node degree clustering")
for v in nodes(G):
- print v,degree(G,v),clustering(G,v)
+ print('%s %d %f' % (v,degree(G,v),clustering(G,v)))
# print the adjacency list to terminal
-write_adjlist(G,sys.stdout)
+try:
+ write_adjlist(G,sys.stdout)
+except TypeError: # Python 3.x
+ write_adjlist(G,sys.stdout.buffer)
diff --git a/examples/graph/expected_degree_sequence.py b/examples/graph/expected_degree_sequence.py
index d86dd9b2..de0ebab1 100644
--- a/examples/graph/expected_degree_sequence.py
+++ b/examples/graph/expected_degree_sequence.py
@@ -18,11 +18,11 @@ n=500 # n nodes
p=0.1
w=[p*n for i in range(n)] # w = p*n for all nodes
G=expected_degree_graph(w) # configuration model
-print "Degree histogram"
-print "degree (#nodes) ****"
+print("Degree histogram")
+print("degree (#nodes) ****")
dh=degree_histogram(G)
low=min(degree(G))
for i in range(low,len(dh)):
bar=''.join(dh[i]*['*'])
- print "%2s (%2s) %s"%(i,dh[i],bar)
+ print("%2s (%2s) %s"%(i,dh[i],bar))
diff --git a/examples/graph/football.py b/examples/graph/football.py
index 95326814..8028fb2b 100644
--- a/examples/graph/football.py
+++ b/examples/graph/football.py
@@ -19,29 +19,32 @@ __author__ = """Aric Hagberg (hagberg@lanl.gov)"""
try:
import pyparsing
-except ImportError,e:
+except ImportError as e:
raise ImportError(str(e)+". Check http://pyparsing.wikispaces.com/")
from networkx import *
url="http://www-personal.umich.edu/~mejn/netdata/football.zip"
-import urllib
-import StringIO
+try: # Python 3.x
+ import urllib.request as urllib
+except ImportError: # Python 2.x
+ import urllib
+import io
import zipfile
sock = urllib.urlopen(url) # open URL
-s=StringIO.StringIO(sock.read()) # read into StringIO "file"
+s=io.BytesIO(sock.read()) # read into BytesIO "file"
sock.close()
zf = zipfile.ZipFile(s) # zipfile object
-txt=zf.read('football.txt') # read info file
-gml=zf.read('football.gml') # read gml data
+txt=zf.read('football.txt').decode() # read info file
+gml=zf.read('football.gml').decode() # read gml data
# throw away bogus first line with # from mejn files
gml=gml.split('\n')[1:]
G=parse_gml(gml) # parse gml data
-print txt
+print(txt)
# print degree for each team - number of games
for n,d in G.degree_iter():
- print n,d
+ print('%s %d' % (n, d))
diff --git a/examples/graph/karate_club.py b/examples/graph/karate_club.py
index f401b59a..2933aaeb 100644
--- a/examples/graph/karate_club.py
+++ b/examples/graph/karate_club.py
@@ -68,8 +68,8 @@ def karate_graph(create_using=None, **kwds):
row=0
- for line in string.split(zacharydat,'\n'):
- thisrow=map(int,string.split(line,' '))
+ for line in zacharydat.split('\n'):
+ thisrow=list(map(int,line.split(' ')))
for col in range(0,len(thisrow)):
if thisrow[col]==1:
G.add_edge(row,col) # col goes from 0,33
@@ -79,6 +79,6 @@ def karate_graph(create_using=None, **kwds):
if __name__ == "__main__":
G=karate_graph()
- print "Node Degree"
+ print("Node Degree")
for v in G:
- print v,G.degree(v)
+ print('%s %s' % (v,G.degree(v)))
diff --git a/examples/graph/knuth_miles.py b/examples/graph/knuth_miles.py
index 4c5b50e9..11c1ddc1 100644
--- a/examples/graph/knuth_miles.py
+++ b/examples/graph/knuth_miles.py
@@ -34,11 +34,8 @@ def miles_graph():
from the Stanford GraphBase.
"""
# open file miles_dat.txt.gz (or miles_dat.txt)
- try:
- import gzip
- fh = gzip.open('knuth_miles.txt.gz','r')
- except:
- fh=open("knuth_miles.txt","r")
+ import gzip
+ fh = gzip.open('knuth_miles.txt.gz','r')
G=nx.Graph()
G.position={}
@@ -46,6 +43,7 @@ def miles_graph():
cities=[]
for line in fh.readlines():
+ line = line.decode()
if line.startswith("*"): # skip comments
continue
@@ -76,9 +74,9 @@ if __name__ == '__main__':
G=miles_graph()
- print "Loaded miles_dat.txt containing 128 cities."
- print "digraph has %d nodes with %d edges"\
- %(nx.number_of_nodes(G),nx.number_of_edges(G))
+ print("Loaded miles_dat.txt containing 128 cities.")
+ print("digraph has %d nodes with %d edges"\
+ %(nx.number_of_nodes(G),nx.number_of_edges(G)))
# make new graph of cites, edge if less then 300 miles between them
diff --git a/examples/graph/napoleon_russian_campaign.py b/examples/graph/napoleon_russian_campaign.py
index 8dd9053d..d9ee0afb 100644
--- a/examples/graph/napoleon_russian_campaign.py
+++ b/examples/graph/napoleon_russian_campaign.py
@@ -12,7 +12,6 @@ __author__ = """Aric Hagberg (hagberg@lanl.gov)"""
# All rights reserved.
# BSD license.
-import matplotlib.pyplot as plt
import string
import networkx as nx
@@ -94,8 +93,8 @@ def minard_graph():
36.5,55.0,Malo-Jarosewii"""
c={}
- for line in string.split(cities,'\n'):
- x,y,name=string.split(line,',')
+ for line in cities.split('\n'):
+ x,y,name=line.split(',')
c[name]=(float(x),float(y))
g=[]
@@ -106,14 +105,14 @@ def minard_graph():
G.pos={} # location
G.pop={} # size
last=None
- for line in string.split(data,'\n'):
- x,y,p,r,n=string.split(line,',')
+ for line in data.split('\n'):
+ x,y,p,r,n=line.split(',')
G.pos[i]=(float(x),float(y))
G.pop[i]=int(p)
if last is None:
last=i
else:
- G.add_edge(i,last,(r,int(n)))
+ G.add_edge(i,last,{r:int(n)})
last=i
i=i+1
g.append(G)
@@ -124,18 +123,22 @@ if __name__ == "__main__":
(g,city)=minard_graph()
- plt.figure(1,figsize=(11,5))
- plt.clf()
- colors=['b','g','r']
- for G in g:
- c=colors.pop(0)
- node_size=[int(G.pop[n]/300.0) for n in G]
- nx.draw_networkx_edges(G,G.pos,edge_color=c,width=4,alpha=0.5)
- nx.draw_networkx_nodes(G,G.pos,node_size=node_size,node_color=c,alpha=0.5)
- nx.draw_networkx_nodes(G,G.pos,node_size=5,node_color='k')
+ try:
+ import matplotlib.pyplot as plt
+ plt.figure(1,figsize=(11,5))
+ plt.clf()
+ colors=['b','g','r']
+ for G in g:
+ c=colors.pop(0)
+ node_size=[int(G.pop[n]/300.0) for n in G]
+ nx.draw_networkx_edges(G,G.pos,edge_color=c,width=4,alpha=0.5)
+ nx.draw_networkx_nodes(G,G.pos,node_size=node_size,node_color=c,alpha=0.5)
+ nx.draw_networkx_nodes(G,G.pos,node_size=5,node_color='k')
- for c in city:
- x,y=city[c]
- plt.text(x,y+0.1,c)
- plt.savefig("napoleon_russian_campaign.png")
+ for c in city:
+ x,y=city[c]
+ plt.text(x,y+0.1,c)
+ plt.savefig("napoleon_russian_campaign.png")
+ except ImportError:
+ pass
diff --git a/examples/graph/roget.py b/examples/graph/roget.py
index a6d3526b..be633f92 100644
--- a/examples/graph/roget.py
+++ b/examples/graph/roget.py
@@ -20,6 +20,7 @@ References.
"""
+from __future__ import print_function
__author__ = """Brendt Wohlberg\nAric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2005-04-01 07:56:22 -0700 (Fri, 01 Apr 2005) $"
__credits__ = """"""
@@ -40,15 +41,13 @@ def roget_graph():
the Stanford Graph Base.
"""
# open file roget_dat.txt.gz (or roget_dat.txt)
- try:
- import gzip
- fh=gzip.open('roget_dat.txt.gz','r')
- except:
- fh=open("roget_dat.txt","r")
+ import gzip
+ fh=gzip.open('roget_dat.txt.gz','r')
G=DiGraph()
for line in fh.readlines():
+ line = line.decode()
if line.startswith("*"): # skip comments
continue
if line.startswith(" "): # this is a continuation line, append
@@ -67,7 +66,7 @@ def roget_graph():
for tail in tails.split():
if head==tail:
- print >>sys.stderr,"skipping self loop",head,tail
+ print("skipping self loop",head,tail, file=sys.stderr)
G.add_edge(head,tail)
return G
@@ -75,9 +74,9 @@ def roget_graph():
if __name__ == '__main__':
from networkx import *
G=roget_graph()
- print "Loaded roget_dat.txt containing 1022 categories."
- print "digraph has %d nodes with %d edges"\
- %(number_of_nodes(G),number_of_edges(G))
+ print("Loaded roget_dat.txt containing 1022 categories.")
+ print("digraph has %d nodes with %d edges"\
+ %(number_of_nodes(G),number_of_edges(G)))
UG=G.to_undirected()
- print number_connected_components(UG),"connected components"
+ print(number_connected_components(UG),"connected components")
diff --git a/examples/graph/unix_email.py b/examples/graph/unix_email.py
index b1f87230..f7d42979 100755
--- a/examples/graph/unix_email.py
+++ b/examples/graph/unix_email.py
@@ -24,7 +24,7 @@ __author__ = """Aric Hagberg (hagberg@lanl.gov)"""
# BSD license.
import email
-from email.Utils import getaddresses,parseaddr
+from email.utils import getaddresses,parseaddr
import mailbox
import sys
@@ -48,12 +48,11 @@ if __name__ == '__main__':
pass
if len(sys.argv)==1:
- file="unix_email.mbox"
+ filePath = "unix_email.mbox"
else:
- file=sys.argv[1]
- fp=open(file,"r")
+ filePath = sys.argv[1]
- mbox = mailbox.UnixMailbox(fp, msgfactory) # parse unix mailbox
+ mbox = mailbox.mbox(filePath, msgfactory) # parse unix mailbox
G=nx.MultiDiGraph() # create empty graph
@@ -73,7 +72,7 @@ if __name__ == '__main__':
# print edges with message subject
for (u,v,d) in G.edges_iter(data=True):
- print "From: %s To: %s Subject: %s"%(u,v,d['message']["Subject"])
+ print("From: %s To: %s Subject: %s"%(u,v,d['message']["Subject"]))
try: # draw
diff --git a/examples/graph/words.py b/examples/graph/words.py
index 2f1660d2..7411611b 100644
--- a/examples/graph/words.py
+++ b/examples/graph/words.py
@@ -58,49 +58,47 @@ def words_graph():
""" Return the words example graph from the Stanford GraphBase"""
import sys
- # open file words_dat.txt.gz (or words_dat.txt)
- try:
- import gzip
- fh=gzip.open('words_dat.txt.gz','r')
- except:
- fh=open("words_dat.txt","r")
+ # open file words_dat.txt.gz
+ import gzip
+ fh=gzip.open('words_dat.txt.gz','r')
G = Graph(name="words")
sys.stderr.write("Loading words_dat.txt: ")
for line in fh.readlines():
+ line = line.decode()
if line.startswith("*"):
continue
w=line[0:5]
G.add_node(w)
nwords=number_of_nodes(G)
words=G.nodes()
- for k in xrange(0,nwords):
+ for k in range(0,nwords):
if (k%100==0):
sys.stderr.softspace=0
sys.stderr.write(".")
- for l in xrange(k+1,nwords):
+ for l in range(k+1,nwords):
if _wdist(words[k],words[l]) == 1:
G.add_edge(words[k],words[l])
+ print()
return G
if __name__ == '__main__':
from networkx import *
G=words_graph()
- print "Loaded words_dat.txt containing 5757 five-letter English words."
- print "Two words are connected if they differ in one letter."
- print "graph has %d nodes with %d edges"\
- %(number_of_nodes(G),number_of_edges(G))
+ print("Loaded words_dat.txt containing 5757 five-letter English words.")
+ print("Two words are connected if they differ in one letter.")
+ print("graph has %d nodes with %d edges"
+ %(number_of_nodes(G),number_of_edges(G)))
sp=shortest_path(G, 'chaos', 'order')
- print "shortest path between 'chaos' and 'order' is:\n", sp
+ print("shortest path between 'chaos' and 'order' is:\n%s" % sp)
sp=shortest_path(G, 'nodes', 'graph')
- print "shortest path between 'nodes' and 'graph' is:\n", sp
+ print("shortest path between 'nodes' and 'graph' is:\n%s" % sp)
sp=shortest_path(G, 'pound', 'marks')
- print "shortest path between 'pound' and 'marks' is:\n", sp
+ print("shortest path between 'pound' and 'marks' is:\n%s" % sp)
- print number_connected_components(G),"connected components"
+ print("%d connected components" % number_connected_components(G))
-