annotate scripts/comment_parser.py @ 1769:30b6a1e7537b

Comment and rating scripts: robust against audioholders without id or audioelements; fixes issue where plots were not cleared before adding new content; showing legend optional; robust against non-UTF8 characters in legend names
author Brecht De Man <b.deman@qmul.ac.uk>
date Mon, 15 Jun 2015 13:09:46 +0100
parents 070c56725b60
children ab79d76c6f85
rev   line source
b@1597 1 import xml.etree.ElementTree as ET
b@1597 2 import os
b@1597 3 import csv
b@1597 4
b@1597 5 # get every XML file in folder
b@1597 6 for file in os.listdir("."): # You have to put this script in folder where output XML files are.
b@1597 7 if file.endswith(".xml"):
b@1597 8 tree = ET.parse(file)
b@1597 9 root = tree.getroot()
b@1597 10
b@1598 11 # get list of all page names
b@1598 12 for audioholder in root.findall("./audioholder"): # iterate over pages
b@1598 13 page_name = audioholder.get('id') # get page name
b@1769 14
b@1769 15 if page_name is None: # ignore 'empty' audio_holders
b@1769 16 break
b@1597 17
b@1598 18 # create folder [page_name] if not yet created
b@1598 19 if not os.path.exists(page_name):
b@1598 20 os.makedirs(page_name)
b@1597 21
b@1598 22 # for page [page_name], print comments related to fragment [id]
b@1598 23 for audioelement in root.findall("*/[@id='"+page_name+"']/audioelement"):
b@1769 24 if audioelement is not None: # Check it exists
b@1769 25 audio_id = str(audioelement.get('id'))
b@1597 26
b@1769 27 # append to file [page_name]/[page_name]-comments-[id].csv
b@1769 28 with open(page_name+'/'+page_name+'-comments-'+audio_id+'.csv', 'a') as csvfile:
b@1769 29 writer = csv.writer(csvfile, delimiter=',')
b@1769 30 commentstr = root.find("*/[@id='"
b@1769 31 + page_name
b@1769 32 + "']/audioelement/[@id='"
b@1769 33 + audio_id
b@1769 34 + "']/comment/response").text
b@1769 35 if commentstr is None:
b@1769 36 writer.writerow([''])
b@1769 37 else:
b@1769 38 writer.writerow([commentstr.encode("utf-8")])
b@1769 39 #TODO Comma doesn't act as delimiter now!
b@1769 40 # (when adding more than just a comment per line):
b@1769 41 # writer.writerow([file + ',' + commentstr.encode("utf-8")])
b@1597 42
b@1769 43 #TODO Replace 'new line' with something else?
nickjillings@1601 44
b@1769 45 #TODO 'Append' means duplicate entries if run several times...
b@1769 46