Job Offer: Python Ninja or Pirate!

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Dec 11 07:18:13 EST 2007


kromakey a écrit :
> On 10 Dec, 19:11, Stargaming <stargam... at gmail.com> wrote:
>> On Mon, 10 Dec 2007 16:10:16 +0200, Nikos Vergas wrote:
>>
>> [snip]
>>
>>>> Problem: In the dynamic language of your choice, write a short program
>>>> that will:
>>>>  1. define a list of the following user ids 42346, 77290, 729 (you can
>>>> hardcode these, but it should
>>>> still work with more or less ids)
>>>>  2. retrieve an xml document related to each user at this url "http://
>>>> api.etsy.com/feeds/xml_user_details.php?id="
>>>>  3. retrieve the data contained in the city element from each xml
>>>> document
>>>>  4. keep a running total of how many users are found in each city 5.
>>>>  display the total count of users living in each city
>> [snip]
>>
(snip)
> 
> A simpleton's version:
> 
> #!/usr/local/bin/python
> 
> import urllib
> from elementtree import ElementTree as et
> 
> userids = [71234,729,42346,77290,729,729]
> url = 'http://api.etsy.com/feeds/xml_user_details.php?id='
> 
> if __name__ == "__main__":
> 
>   city = {}
>   for userid in userids:
>     feed = urllib.urlopen(url+str(userid))
>     tree = et.parse(feed)
>     for elem in tree.getiterator('city'):
>       if not city.has_key(elem.text):city[elem.text] = 1
>       else: city[elem.text] += 1
>   for k,v in city.items():
>     if not k == None:print k,':\t',v


def count_users_by_city(url, userids):
    urlopen = urllib.urlopen
    parse = et.parse
    cities = {}
    for userid in map(str, userids):
       feed = urlopen(url+userid)
       tree = parse(feed)
       for elem in tree.getiterator('city'):
           key = elem.text
           if key in cities:
               cities[key] += 1
           else:
               cities[key] = 1
    return cities

if __name__ == '__main__':
     cities = count_users_by_city(url, userids)
     print "\n".join("%s:%s" % item for item in cities.items())


Not tested !-)



More information about the Python-list mailing list