nicholas@872: import xml.etree.ElementTree as ET nicholas@872: import os nicholas@872: import csv nicholas@872: nicholas@872: # get every XML file in folder nicholas@872: for file in os.listdir("."): # You have to put this script in folder where output XML files are. nicholas@872: if file.endswith(".xml"): nicholas@872: tree = ET.parse(file) nicholas@872: root = tree.getroot() nicholas@872: nicholas@872: # get list of all page names nicholas@872: for audioholder in root.findall("./audioholder"): # iterate over pages nicholas@872: page_name = audioholder.get('id') # get page name nicholas@872: nicholas@872: if page_name is None: # ignore 'empty' audio_holders nicholas@872: break nicholas@872: nicholas@872: # create folder [page_name] if not yet created nicholas@872: if not os.path.exists(page_name): nicholas@872: os.makedirs(page_name) nicholas@872: nicholas@872: # for page [page_name], print comments related to fragment [id] nicholas@872: for audioelement in root.findall("*/[@id='"+page_name+"']/audioelement"): nicholas@872: if audioelement is not None: # Check it exists nicholas@872: audio_id = str(audioelement.get('id')) nicholas@872: nicholas@872: # append to file [page_name]/[page_name]-comments-[id].csv nicholas@872: with open(page_name+'/'+page_name+'-comments-'+audio_id+'.csv', 'a') as csvfile: nicholas@872: writer = csv.writer(csvfile, delimiter=',') nicholas@872: commentstr = root.find("*/[@id='" nicholas@872: + page_name nicholas@872: + "']/audioelement/[@id='" nicholas@872: + audio_id nicholas@872: + "']/comment/response").text nicholas@872: if commentstr is None: nicholas@872: writer.writerow(['']) nicholas@872: else: nicholas@872: writer.writerow([commentstr.encode("utf-8")]) nicholas@872: #TODO Comma doesn't act as delimiter now! nicholas@872: # (when adding more than just a comment per line): nicholas@872: # writer.writerow([file + ',' + commentstr.encode("utf-8")]) nicholas@872: nicholas@872: #TODO Replace 'new line' with something else? nicholas@872: nicholas@872: #TODO 'Append' means duplicate entries if run several times... nicholas@872: