Programming Idiomatic Code

Nathan Harmston ratchetgrid at
Tue Jul 3 02:22:04 CEST 2007


I m sorry but I m bored at work (and no ones looking so I can write
some Python) and following a job advertisement post,I decided to write
the code to do its for the one entitled Ninjas or something like that.
I was wondering what could be done to my following code to make it
more idiomatic...or whether it was idiomatic and to be honest what
idiomatic really means. All comments greatly appreciated and welcomed.

Thanks in advance


import urllib2,sys
from elementtree.ElementTree import parse

base_url = ""

def read_id_file(filename):
    """ reads a file and generates a list of ids from it"""
    ids = [ ]
	id_file = open(filename, "r")
	for l in id_file:
            ids.append( l.strip("\n") )
    except e:
        print e
    return ids

def generate_count(id_list):
    """ takes a list of ids and returns a dictionary of cities with
associated counts"""
    city_count = {}
    for i in id_list:
    	url = "%s%s" %(base_url,i)
	req = urllib2.Request(url)
            xml = parse(urllib2.urlopen(url)).getroot()
            city  = xml.findtext('user/city')
	except e:
            print e.reason
            city_count[city] += 1
            city_count[city] = 1
    return city_count

if __name__=='__main__':
    if len(sys.argv) is 1:
        id_list = [ 42346, 77290, 729 ]
        try: id_list = read_id_file(sys.argv[1])
        except e: print e
    for k, v in generate_count(id_list).items():
        print "%s: %i" %(k, v)

More information about the Python-list mailing list