N
Nathan Harmston
Hi,
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
Nathan
import urllib2,sys
from elementtree.ElementTree import parse
base_url = "http://api.etsy.com/feeds/xml_user_details.php?id="
def read_id_file(filename):
""" reads a file and generates a list of ids from it"""
ids = [ ]
try:
id_file = open(filename, "r")
for l in id_file:
ids.append( l.strip("\n") )
id_file.close()
except e:
print e
os._exit(99)
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)
try:
xml = parse(urllib2.urlopen(url)).getroot()
city = xml.findtext('user/city')
except e:
print e.reason
os._exit(99)
try:
city_count[city] += 1
except:
city_count[city] = 1
return city_count
if __name__=='__main__':
if len(sys.argv) is 1:
id_list = [ 42346, 77290, 729 ]
else:
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)
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
Nathan
import urllib2,sys
from elementtree.ElementTree import parse
base_url = "http://api.etsy.com/feeds/xml_user_details.php?id="
def read_id_file(filename):
""" reads a file and generates a list of ids from it"""
ids = [ ]
try:
id_file = open(filename, "r")
for l in id_file:
ids.append( l.strip("\n") )
id_file.close()
except e:
print e
os._exit(99)
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)
try:
xml = parse(urllib2.urlopen(url)).getroot()
city = xml.findtext('user/city')
except e:
print e.reason
os._exit(99)
try:
city_count[city] += 1
except:
city_count[city] = 1
return city_count
if __name__=='__main__':
if len(sys.argv) is 1:
id_list = [ 42346, 77290, 729 ]
else:
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)