Skip to content

Instantly share code, notes, and snippets.

@fhardison
Last active March 17, 2020 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fhardison/7b8125ef4ea1fdbeedaed9147406f1c1 to your computer and use it in GitHub Desktop.
Save fhardison/7b8125ef4ea1fdbeedaed9147406f1c1 to your computer and use it in GitHub Desktop.
A extensible functional method of building generating an html from the format used by Greek Learners Text Project
import sys
import re
import mistletoe
def read_to_dict(fpath, encoding='UTF-8'):
lines = {}
with open(fpath, 'r', encoding=encoding) as file:
for line in file:
num, content = line.split(' ', maxsplit=1)
lines[num] = content
return lines
def default(num, cons):
return mistletoe.markdown(cons)
FNCOUNT = 0
def footnote_cons(line_num, cons):
return f"""<label for="ln-{line_num}" class="margin-toggle sidenote-number"></label>
<input type="checkbox" id="ln-{line_num}" class="margin-toggle"/>
<span class="sidenote">{cons.strip()}</span>"""
def footnote(num, cons, lines, no_output):
marker = num.split('.')[-1]
line_num = num.replace('.' + marker, '')
target_line = lines[line_num]
footnote_num = re.search(r'\[([^\]]+).fn\]', target_line).group(0)
global FNCOUNT
FNCOUNT += 1
lines[line_num] = target_line.replace(footnote_num,
footnote_cons(line_num, cons))
no_output.append(num)
return '' # finish func
def header(num, cons, lines, no_output):
lines[num] = f"<h1>{default(cons)}</h1>"
# Apply to specific lines based on the end of the line ref
marker_renderers = {"fn": footnote,
"head": header}
# Can apply to every line if a condition is met,
# If you want it to apply to each line, return True
# as shown below with the default
line_renderers = [(lambda num, cons: True, default)]
ifile = sys.argv[1]
lines = read_to_dict(ifile)
no_output = []
for num, cons in lines.items():
marker = num.split('.')[-1]
if marker in marker_renderers:
print(marker_renderers[marker](num, cons, lines, no_output), end='')
TITLE = ''
#Your CSS file of choice. This one enable the margin notes to work
CSS_FILE = 'tufte.min.css'
#URL for the index page for this projects site, if there is one
REPO_HOME = ''
PROJECT_NAME = 'Cool GLTP project'
HEADER = f"""
<!DOCTYPE html>
<html lang="grc">
<head>
<title>{TITLE}</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Noto+Serif:400,700&amp;subset=greek,greek-ext" rel="stylesheet">
<link href="{CSS_FILE}" rel="stylesheet">
</head>
<body>
<article>
<nav>&#x2191; <a href="{REPO_HOME}">{PROJECT_NAME}</a></nav>
<h1 lang="en">{TITLE}</h1>
<section>
"""
FOOTER = """\
</section>
</article>
</body>
</html>
"""
print(HEADER)
for num, cons in lines.items():
if num not in no_output:
for applies, f in line_renderers:
if applies(num, cons):
print(default(cons))
print(FOOTER)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment