I'm a beginner and have written my first Python module that parses a XML file containing some events and prints them out to stdout
as JSON. I would appreciate some feedback about design, code layout, best practices, what can be optimized and so on.
from __future__ import with_statement
import json
import xml.etree.ElementTree as etree
def _sanitize_string(string):
"""docstring for _clean_string"""
string = string.replace('\n', '').split()
return ' '.join(string)
class Event(object):
"""docstring for Event"""
def __init__(self, date, event, organizer, time, venue):
self.date = date
self.event = event
self.organizer = organizer
self.time = time
self.venue = venue
def provide_data(self):
"""docstring for provide_data"""
data = {}
data['date'] = self.date
data['event'] = self.event
data['organizer'] = self.organizer
data['time'] = self.time
data['venue'] = self.venue
return data
class EventCollection(list):
"""docstring for EventCollection"""
def __init__(self):
super(EventCollection, self).__init__([])
def as_json(self):
"""docstring for as_json"""
print json.dumps([event.provide_data() for event in self],
sort_keys=True, indent=2)
def read_file(event_collection, filename='events.xml'):
"""docstring for read_file"""
try:
with open(filename) as f:
tree = etree.parse(f)
for row in tree.findall('.//row'):
# event = [_sanitize_string(node.text) for node in row]
# if event[0] and event[0][0].isdigit():
# print event
tmpl = [_sanitize_string(node.text) for node in row]
if tmpl[0] and tmpl[0][0].isdigit():
event = Event(tmpl.pop(0), tmpl.pop(0), tmpl.pop(0),
tmpl.pop(0), tmpl.pop(0))
event_collection.append(event)
except IOError as ioerr:
print "File Error: %s" % str(ioerr)
def main():
"""docstring for main"""
event_collection = EventCollection()
read_file(event_collection)
event_collection.as_json()
# event_collection.as_csv()
if __name__ == '__main__':
main()
string
. It threw me off a little. \$\endgroup\$