Mercurial > js4py
changeset 159:1eb05ae4fd4d core-javascript.closure-exercises
Refactor remove_answers.py to introduce function that reads from src file and writes to tgt file.
| author | jf3243 |
|---|---|
| date | Wed, 09 Nov 2011 15:52:52 +0000 |
| parents | f4ea703a359b |
| children | 8cacef25f3d8 |
| files | core-javascript/py/remove_answers.py |
| diffstat | 1 files changed, 43 insertions(+), 34 deletions(-) [+] |
line wrap: on
line diff
--- a/core-javascript/py/remove_answers.py Wed Nov 09 15:51:55 2011 +0000 +++ b/core-javascript/py/remove_answers.py Wed Nov 09 15:52:52 2011 +0000 @@ -1,16 +1,10 @@ '''Remove answers from exercises file.''' - - import sys - NORMAL, SKIPPING, ERROR = range(3) LINE, SOMETHING, START, STOP = range(4) - - - lookup = {} # All other states are an error. @@ -23,47 +17,62 @@ lookup[SKIPPING, STOP] = NORMAL -filename = 'core-javascript-work/closure-exercises.js' +def doit(src, tgt): -write = sys.stdout.write -with open(filename) as lines: + pending = [] + with open(src, 'rb') as lines: - new_state = NORMAL + new_state = NORMAL - for lineno, line in enumerate(lines): + for lineno, line in enumerate(lines): - state = new_state + state = new_state - stripped_line = line.strip() + stripped_line = line.strip() + + if stripped_line.startswith('something'): + event = SOMETHING - if stripped_line.startswith('something'): - event = SOMETHING + elif stripped_line == '// start': + event = START - elif stripped_line == '// start': - event = START + elif stripped_line == '// stop': + event = STOP - elif stripped_line == '// stop': - event = STOP + else: + event = LINE + + new_state = lookup[state, event] - else: - event = LINE + if event == SOMETHING: + pass - new_state = lookup[state, event] + elif event == STOP: + pass - if event == SOMETHING: - pass + elif event == START: + indent = len(line) - len(line.lstrip()) + spaces = line[0:indent] + pending.append(spaces + '// Please write your answer here.') - elif event == STOP: - pass + elif state == SKIPPING: + pass + + elif event == LINE: + pending.append(line.rstrip()) + - elif event == START: - indent = len(line) - len(line.lstrip()) - spaces = line[0:indent] - write(spaces + '// Please write your answer here.\n') + with open(tgt, 'wb') as f: + + for line in pending: + f.write(line + '\r\n') + + - elif state == SKIPPING: - pass +if __name__ == '__main__': - elif event == LINE: - write(line) + src = 'core-javascript-work/answers/closure-exercises.js' + tgt = 'core-javascript-work/closure-exercises.js' + + doit(src, tgt)
