nickjillings@1528: #!/usr/bin/python nickjillings@1528: # -*- coding: utf-8 -*- nickjillings@1528: nickjillings@1528: import xml.etree.ElementTree as ET nickjillings@1528: import os nickjillings@1528: import csv nickjillings@1528: nickjillings@1528: # XML results files location (modify as needed): nickjillings@1528: folder_name = "../saves" # Looks in 'saves/' folder from 'scripts/' folder nickjillings@1528: nickjillings@1528: # get every XML file in folder nickjillings@1528: for file in os.listdir(folder_name): nickjillings@1528: if file.endswith(".xml"): nickjillings@1528: tree = ET.parse(folder_name + '/' + file) nickjillings@1528: root = tree.getroot() nickjillings@1528: nickjillings@1528: # get list of all page names nickjillings@1528: for audioholder in root.findall("./audioholder"): # iterate over pages nickjillings@1528: page_name = audioholder.get('id') # get page name nickjillings@1528: nickjillings@1528: if page_name is None: # ignore 'empty' audio_holders nickjillings@1528: print "WARNING: " + file + " contains empty audio holder. (comment_parser.py)" nickjillings@1528: break nickjillings@1528: nickjillings@1528: # create folder [page_name] if not yet created nickjillings@1528: if not os.path.exists(folder_name + "/" + page_name): nickjillings@1528: os.makedirs(folder_name + "/" + page_name) nickjillings@1528: nickjillings@1528: # for page [page_name], print comments related to fragment [id] nickjillings@1528: for audioelement in audioholder.findall("./audioelement"): nickjillings@1528: if audioelement is not None: # Check it exists nickjillings@1528: audio_id = str(audioelement.get('id')) nickjillings@1528: nickjillings@1528: csv_name = folder_name +'/' + page_name+'/'+page_name+'-comments-'+audio_id+'.csv' nickjillings@1528: nickjillings@1528: # append (!) to file [page_name]/[page_name]-comments-[id].csv nickjillings@1528: with open(csv_name, 'a') as csvfile: nickjillings@1528: writer = csv.writer(csvfile, nickjillings@1528: delimiter=',', nickjillings@1528: dialect="excel", nickjillings@1528: quoting=csv.QUOTE_ALL) nickjillings@1528: commentstr = audioelement.find("./comment/response").text nickjillings@1528: nickjillings@1528: if commentstr is None: nickjillings@1528: commentstr = ''; nickjillings@1528: nickjillings@1528: # anonymous comments: nickjillings@1528: #writer.writerow([commentstr.encode("utf-8")]) nickjillings@1528: # comments with (file) name: nickjillings@1528: writer.writerow([file[:-4]] + [commentstr.encode("utf-8")]) nickjillings@1528: nickjillings@1528: #TODO Replace 'new line' in comment with something else? nickjillings@1528: nickjillings@1528: # PRO TIP: Change from csv to txt by running this in bash: nickjillings@1528: # $ cd folder_where_csvs_are/ nickjillings@1528: # $ for i in *.csv; do mv "$i" "${i/.csv}".txt; done