Created
July 13, 2012 02:37
-
-
Save mrklein/3102348 to your computer and use it in GitHub Desktop.
Creating flashcards from plain text files for FlipCards app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
import argparse | |
import os.path | |
from json import dump | |
from string import join | |
import time | |
import tempfile | |
import zipfile | |
import shutil | |
import codecs | |
def parse_cli_options(): | |
parser = argparse.ArgumentParser( | |
description='Convert plain test files to Flashcards format') | |
parser.add_argument('-n', '--name', help='Deck name', nargs=1, type=str, | |
default='Default deck name') | |
parser.add_argument('-c', '--color', help='Deck color', nargs=1, type=str, | |
default='blue') | |
parser.add_argument('directory', type=str, nargs=1, | |
help='Directory with plain text files') | |
return parser.parse_args() | |
def add_enumeration(lst): | |
res = [] | |
cnt = 1 | |
for item in lst: | |
res.append(u'%d. %s' % (cnt, item.lower())) | |
cnt += 1 | |
return res | |
if __name__ == '__main__': | |
args = parse_cli_options() | |
directory = args.directory[0] | |
if not os.path.exists(directory): | |
print('%s does not exist. Will exit now.' % directory) | |
sys.exit(1) | |
# Collecting cards | |
flashcards = [] | |
for filename in os.listdir(directory): | |
f = codecs.open(os.path.join(directory, filename), encoding='utf-8') | |
for card in f.read().split('---')[:-2]: | |
vals = card.strip().split('\n') | |
front = vals[0] | |
back = vals[2:] | |
if len(back) > 1: | |
back = add_enumeration(back) | |
else: | |
back = [term.lower() for term in back] | |
flashcards.append([front, u'', join(back, u'\n'), u'']) | |
f.close() | |
# Properties dict | |
properties = { | |
u'modifiedDate': time.time(), | |
u'name': args.name[0], | |
u'color': args.color[0]} | |
# Creating temporary directory for data | |
tmp_dir = tempfile.mkdtemp() | |
data_dir = os.path.join(tmp_dir, properties['name']) | |
os.mkdir(data_dir) | |
f = codecs.open(os.path.join(data_dir, 'data.txt'), encoding='utf-8', | |
mode='w') | |
dump({u'properties': properties, u'flashcards': flashcards}, f, | |
encoding='utf-8', ensure_ascii=False) | |
f.close() | |
# Creating zip file | |
current_dir = os.getcwd() | |
zip_file_name = properties['name'] + '.zip' | |
os.chdir(tmp_dir) | |
archive = zipfile.ZipFile(zip_file_name, 'w') | |
archive.write(os.path.join(properties['name'], 'data.txt')) | |
archive.close() | |
os.rename(zip_file_name, os.path.join(current_dir, zip_file_name)) | |
os.chdir(current_dir) | |
shutil.rmtree(tmp_dir) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment