Skip to content

Instantly share code, notes, and snippets.

@willtownes
Created September 14, 2015 17:14
Show Gist options
  • Save willtownes/085890bff089e28f9d71 to your computer and use it in GitHub Desktop.
Save willtownes/085890bff089e28f9d71 to your computer and use it in GitHub Desktop.
CS281 Convert LaTeX section notes into Python
"""
Python Script to extract code blocks from tex files for CS281
input: a file in current working directory with suffix *.tex
output: the same file with suffix *.py, with everything except the python parts removed
"""
#import pdb
from sys import argv
import os
def convert(ifile,ofile):
"""convert the *.tex file "ifile" to a python representation "ofile" """
with open(ifile) as f, open(ofile,'w') as g:
pymode = False
for line in f:
#pdb.set_trace()
if pymode == True: #in a code block
if "\\end{lstlisting}" in line: #end code block
g.write("\n")
pymode = False
else:
g.write(line)
elif line[:2] == '\\1': #header info, convert to comment
g.write("\n")
g.write("#"+" ".join(line.split("\\1")[1:]))
g.write("\n")
elif "\\begin{lstlisting}" in line: #start code block
pymode = True
if __name__=="__main__":
#ifile = "02/section02.tex"
#ofile = "02/section02.tex.py"
#ifile = "test.tex"
#ofile = "test.tex.py"
try: folder = argv[1] #use folder specified by command line
except IndexError: folder = os.getcwd() #if no folder provided, use default of current directory
for fname in os.listdir(folder):
if os.path.splitext(fname)[1]==".tex":
print("Creating file %s.py"%fname)
convert(os.path.join(folder,fname),os.path.join(folder,fname+".py"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment