Skip to content

Instantly share code, notes, and snippets.

@naojitaniguchi
Created August 14, 2015 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naojitaniguchi/706e2932e4183f5c73c1 to your computer and use it in GitHub Desktop.
Save naojitaniguchi/706e2932e4183f5c73c1 to your computer and use it in GitHub Desktop.
parsing XML and sorting by class member sample
__author__ = 'tani'
from xml.etree.ElementTree import *
from operator import itemgetter, attrgetter
class Question:
def __init__(self, delayTime, comment):
self.delayTime = delayTime
self.comment = comment
def __repr__(self):
return repr((self.delayTime, self.comment))
tree = parse("question_selected_easy.xml")
elem = tree.getroot()
questionList = []
for e in elem.getiterator("Orca"):
#print e.get("DelayTimeMS")
#print e.get("Comment")
q = Question(e.get("DelayTimeMS"), e.get("Comment"))
questionList.append(q)
def numeric_compare(x, y):
return int(x) - int(y)
sortedList = sorted(questionList, key=attrgetter('delayTime'), cmp=numeric_compare)
for q in sortedList:
#print q.comment
splitedComment = q.comment.split(" ")
csvLine = splitedComment[0] + "," + splitedComment[1] + "," + splitedComment[2] + "," + q.delayTime
if ( len(splitedComment) == 4 ):
csvLine += "," + splitedComment[3]
print csvLine
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment