Skip to content

Instantly share code, notes, and snippets.

@gulan
Created July 22, 2015 01:45
Show Gist options
  • Select an option

  • Save gulan/e0964783e6c6fcf8263b to your computer and use it in GitHub Desktop.

Select an option

Save gulan/e0964783e6c6fcf8263b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Convert an 'elide' file to a flashy card file.
A subject.elide file has entries of the form:
answer
question
question
question
... any number of questions
answer
question
question
... and so on
... any number of answer/question entries.
The input file may have blank lines, which will be skipped, as will
standard # comments. The resulting file will have the logical BNF
structure:
elide-file := entry*
entry := answer + question-list
question-list := question*
question := ' ' + prompt
answer, prompt := string + newline
The card file is described elsewhere, but briefly, it is an iteration
lines of the form
question + ' | ' + answer
If the reader just yields (question,answer) pairs, formatting the
output would be trivial.
I would like to write process_input() function as defined below. To do
so I need a elide_reader class. It is also defined below.
"""
import re
import sys
def scan(fh): # Standard comment and blank line stripper
for line in fh:
if re.match(r'^(\s|#)*$',line):
continue # skip line if it has only whitespace and #
if re.match(r'^\s*#',line):
continue # skip line if its first non-blank is #
parts = line.rstrip().split('#')
yield parts[0] + '\n'
class elide_reader(object):
# Procedures presented in systematic development order.
@property
def more_entries(self):
return self.buf != ''
@property
def more_questions(self):
if self.more_entries:
return self.buf.startswith(' ')
return False
def read(self):
line = self.buf
self._read()
return line
def _read(self):
try:
self.buf = self.fh.next()
except StopIteration:
self.buf = ''
def __init__(self,fh):
self.fh = fh
self._read()
def process_input(fo):
while fo.more_entries:
answer = fo.read()
while fo.more_questions:
question = fo.read()
yield (question,answer)
def main():
efile = scan(sys.stdin)
for q,a in process_input(elide_reader(efile)):
q = q.strip()
a = a.strip()
print '%s | %s' % (q,a)
main()
testdata = """# About Topeka
Topeka is the capitol of Kansas.
? is the capitol of Kansas.
Topeka is the capitol of ?.
The city of Topeka was founded in 1857. # official charter
The city of Topeka was founded in ?.
As of the 2000 census, there were 122,377 people living In Topeka.
As of the ? census, there were 122,377 people living In Topeka.
As of the 2000 census, there were ? people living In Topeka.
"""
# print testdata
# mea culpa:
# I forgot to import sys
# In main, I forgot to use elide_reader.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment