annotate scripts/comment_parser.py @ 872:ca4ae613f1dd

Bug Fix #1303 on main
author Nicholas Jillings <nicholas.jillings@eecs.qmul.ac.uk>
date Thu, 25 Jun 2015 16:40:11 +0100
parents
children 302926cdf3c4 a049c6cf7eb3
rev   line source
nicholas@872 1 import xml.etree.ElementTree as ET
nicholas@872 2 import os
nicholas@872 3 import csv
nicholas@872 4
nicholas@872 5 # get every XML file in folder
nicholas@872 6 for file in os.listdir("."): # You have to put this script in folder where output XML files are.
nicholas@872 7 if file.endswith(".xml"):
nicholas@872 8 tree = ET.parse(file)
nicholas@872 9 root = tree.getroot()
nicholas@872 10
nicholas@872 11 # get list of all page names
nicholas@872 12 for audioholder in root.findall("./audioholder"): # iterate over pages
nicholas@872 13 page_name = audioholder.get('id') # get page name
nicholas@872 14
nicholas@872 15 if page_name is None: # ignore 'empty' audio_holders
nicholas@872 16 break
nicholas@872 17
nicholas@872 18 # create folder [page_name] if not yet created
nicholas@872 19 if not os.path.exists(page_name):
nicholas@872 20 os.makedirs(page_name)
nicholas@872 21
nicholas@872 22 # for page [page_name], print comments related to fragment [id]
nicholas@872 23 for audioelement in root.findall("*/[@id='"+page_name+"']/audioelement"):
nicholas@872 24 if audioelement is not None: # Check it exists
nicholas@872 25 audio_id = str(audioelement.get('id'))
nicholas@872 26
nicholas@872 27 # append to file [page_name]/[page_name]-comments-[id].csv
nicholas@872 28 with open(page_name+'/'+page_name+'-comments-'+audio_id+'.csv', 'a') as csvfile:
nicholas@872 29 writer = csv.writer(csvfile, delimiter=',')
nicholas@872 30 commentstr = root.find("*/[@id='"
nicholas@872 31 + page_name
nicholas@872 32 + "']/audioelement/[@id='"
nicholas@872 33 + audio_id
nicholas@872 34 + "']/comment/response").text
nicholas@872 35 if commentstr is None:
nicholas@872 36 writer.writerow([''])
nicholas@872 37 else:
nicholas@872 38 writer.writerow([commentstr.encode("utf-8")])
nicholas@872 39 #TODO Comma doesn't act as delimiter now!
nicholas@872 40 # (when adding more than just a comment per line):
nicholas@872 41 # writer.writerow([file + ',' + commentstr.encode("utf-8")])
nicholas@872 42
nicholas@872 43 #TODO Replace 'new line' with something else?
nicholas@872 44
nicholas@872 45 #TODO 'Append' means duplicate entries if run several times...
nicholas@872 46