|
| 1 | +# Online Python Tutor |
| 2 | +# Copyright (C) 2010 Philip J. Guo |
| 3 | +# https://github.com/pgbovine/OnlinePythonTutor/ |
| 4 | +# |
| 5 | +# This program is free software: you can redistribute it and/or modify |
| 6 | +# it under the terms of the GNU General Public License as published by |
| 7 | +# the Free Software Foundation, either version 3 of the License, or |
| 8 | +# (at your option) any later version. |
| 9 | +# |
| 10 | +# This program is distributed in the hope that it will be useful, |
| 11 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +# GNU General Public License for more details. |
| 14 | +# |
| 15 | +# You should have received a copy of the GNU General Public License |
| 16 | +# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | + |
| 18 | +# Defines a function that parses an Online Python Tutor 'questions file' |
| 19 | +# into a dict, which can easily be converted into JSON |
| 20 | + |
| 21 | +import os, sys |
| 22 | + |
| 23 | +delimiters = set(['Name:', 'Question:', 'Hint:', 'Solution:', |
| 24 | +'Skeleton:', 'Test:', 'Expect:']) |
| 25 | + |
| 26 | +def parseQuestionsFile(filename): |
| 27 | + ret = {} |
| 28 | + |
| 29 | + curParts = [] |
| 30 | + curDelimiter = None |
| 31 | + |
| 32 | + for line in open(filename): |
| 33 | + # only strip TRAILING spaces and not leading spaces |
| 34 | + line = line.rstrip() |
| 35 | + |
| 36 | + if line in delimiters: |
| 37 | + if curDelimiter == 'Name:': |
| 38 | + ret['name'] = '\n'.join(curParts).strip() |
| 39 | + elif curDelimiter == 'Question:': |
| 40 | + ret['question'] = ' '.join(curParts).strip() |
| 41 | + elif curDelimiter == 'Hint:': |
| 42 | + ret['hint'] = ' '.join(curParts).strip() |
| 43 | + elif curDelimiter == 'Solution:': |
| 44 | + ret['solution'] = ' '.join(curParts).strip() |
| 45 | + elif curDelimiter == 'Skeleton:': |
| 46 | + ret['skeleton'] = '\n'.join(curParts).strip() |
| 47 | + |
| 48 | + curDelimiter = line |
| 49 | + curParts = [] |
| 50 | + else: |
| 51 | + curParts.append(line) |
| 52 | + |
| 53 | + if curDelimiter: |
| 54 | + ret[curDelimiter] = '\n'.join(curParts) |
| 55 | + |
| 56 | + return ret |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + import pprint |
| 61 | + pp = pprint.PrettyPrinter(indent=2) |
| 62 | + print pp.pprint(parseQuestionsFile(sys.argv[1])) |
0 commit comments