[python-users] FrOSCon Poster "Python"

Christopher Arndt chris.arndt at web.de
Di Aug 17 19:31:19 CEST 2010


Andreas Schreiber schrieb:
> Anregungen irgendjemand?

Hier ein schönes praktisches Anwendungsbeispiel, das die "batteries
includes"-Eigenschaft von Python zeigt:

Python als HTTP-Client und CSV-Parser:

>>> import csv, urllib
>>> result = urllib.urlopen(
        'http://www.andrewpatton.com/countrylist.csv')
>>> countries = [c for c in csv.DictReader(result)]
>>> from pprint import pprint
>>> pprint(countries[0])
{'Capital': 'Kabul',
 'Common Name': 'Afghanistan',
 'Formal Name': 'Islamic State of Afghanistan',
 'IANA Country Code TLD': '.af',
 'ISO 3166-1 2 Letter Code': 'AF',
 'ISO 3166-1 3 Letter Code': 'AFG',
 'ISO 3166-1 Number': '004',
 'ISO 4217 Currency Code': 'AFN',
 'ISO 4217 Currency Name': 'Afghani',
 'ITU-T Telephone Code': '+93',
 'Sort Order': '1',
 'Sovereignty': '',
 'Sub Type': '',
 'Type': 'Independent State'}

Oder so:

>>> countries = {}
>>> for country in csv.DictReader(result):
...     countries[country['ISO 3166-1 2 Letter Code']] = country
>>> pprint(countries['DE'])
{'Capital': 'Berlin',
 'Common Name': 'Germany',
 'Formal Name': 'Federal Republic of Germany',
 'IANA Country Code TLD': '.de',
 'ISO 3166-1 2 Letter Code': 'DE',
 'ISO 3166-1 3 Letter Code': 'DEU',
 'ISO 3166-1 Number': '276',
 'ISO 4217 Currency Code': 'EUR',
 'ISO 4217 Currency Name': 'Euro',
 'ITU-T Telephone Code': '+49',
 'Sort Order': '64',
 'Sovereignty': '',
 'Sub Type': '',
 'Type': 'Independent State'}


Hier wären natürlich die Dictionary-Comprehensions von Python >= 2.7
noch schöner.


Chris



Mehr Informationen über die Mailingliste python-users