1 #!/usr/bin/env python 2 3 """ 4 Collect responses from multiple answer files. 5 """ 6 7 from XSLForms.Resources.WebResources import resources 8 from glob import glob 9 import os 10 import libxml2dom 11 12 question_path = "/questionnaire/question" 13 14 def collect(questions, responses_dir): 15 answers = {} 16 for filename in glob(os.path.join(responses_dir, "distilled-*")): 17 responses = libxml2dom.parse(filename) 18 collect_answers(answers, questions, responses) 19 return answers 20 21 def collect_answers(answers, questions, responses): 22 23 # Get a mapping from questions to responses. 24 25 for n, (question, response_question) in enumerate(map(None, questions.xpath(question_path), responses.xpath(question_path))): 26 27 # Each response container can contain a number of responses. 28 29 for response in response_question.xpath("response"): 30 31 # Get the question number (starting from 1) and the selected response, 32 # if any. 33 34 qn = n + 1 35 selected = response.getAttribute("selected") 36 if selected is None: 37 continue 38 39 # Determine the selected response and whether a textual answer is 40 # expected. 41 42 selected = int(selected) 43 textual_answer = bool(question.xpath("choice[position() = %d]/response-type[@value != 'choice']" % selected)) 44 45 # Collect the answer. 46 47 if not answers.has_key(qn): 48 answers[qn] = {} 49 if not answers[qn].has_key(selected): 50 if textual_answer: 51 answers[qn][selected] = [] 52 else: 53 answers[qn][selected] = 0 54 55 # Either record counts or specific answers. 56 57 if textual_answer: 58 text = response.getAttribute("response-text") 59 if text: 60 answers[qn][selected].append(text) 61 else: 62 answers[qn][selected] += 1 63 64 if __name__ == "__main__": 65 resource_dir = resources(__file__) 66 responses_dir = os.path.join(os.getcwd(), "Responses") 67 questions = libxml2dom.parse(os.path.join(resource_dir, "questions.xml")) 68 answers = collect(questions, responses_dir) 69 70 # Get the collected answers in order. 71 72 items = answers.items() 73 items.sort() 74 75 # Visit each answer record... 76 77 for qn, answers_for_question in items: 78 question = questions.xpath(question_path + ("[position() = %d]" % qn))[0] 79 print "Question %d: %s" % (qn, question.getAttribute("question-text").strip()) 80 81 # Get the response details in order. 82 83 items_for_question = answers_for_question.items() 84 items_for_question.sort() 85 86 # Visit each distinct kind of response. 87 88 for selected, results in items_for_question: 89 choice = question.xpath("choice[position() = %d]" % selected)[0] 90 choice_text = choice.getAttribute("response-choice").strip() 91 if choice_text: 92 print " ", ("%s:" % choice_text), 93 94 if isinstance(results, int): 95 print results 96 else: 97 print 98 sorted_results = results[:] 99 sorted_results.sort() 100 for result in sorted_results: 101 print " ", result 102 103 print 104 105 # vim: tabstop=4 expandtab shiftwidth=4