February 12, 2006

CSV Python code improvement

Having been for a swim and not thought about the code in a previous article, looking at it again it struck me that it could be simpler, so here's the simpler version:

import sys
nodes = {}
lines = sys.stdin.readlines()[2:-2]
class Node:
    def __init__(self,name):
        self.name=name
        self.incoming=0
        self.outgoing=0
for line in lines:
    source, destination = line.split(" -> ")
    destination = destination[:-2]
    nodes.setdefault(destination,Node(destination)).incoming += 1
    nodes.setdefault(source,Node(source)).outgoing += 1
print "incoming,node name,outgoing"
for node in nodes.values():
    print str(node.incoming)+","+node.name+","+str(node.outgoing)

I'd have posted it as a comment, but I couldn't work out how to get it to format correctly without putting in more effort than it was worth.

Posted by ivan at February 12, 2006 5:58 PM
Copyright (c) 2004-2007 Ivan Moore