Created
February 20, 2013 19:17
-
-
Save lsaravia/4998351 to your computer and use it in GitHub Desktop.
A python script to transform <center>![Caption](figs/figure.png)</center> to \centerline{\includegraphics[height=1.5in]{figs/figure.png}} done by guys at http://software-carpentry.org/bootcamps/office-hours.html. This is useful to transform markdown slides written to generate HTML slides, to slides for beamer http://waterthinking.blogspot.com.ar…
This file contains 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 re | |
Usage = """ run with the source file as an argument | |
capture the output with redirection > | |
takes a file with image source in <center> tags, | |
either on 3 lines or one, and reformats to one line | |
As per the OutString variable""" | |
if len(sys.argv)<2: | |
sys.stderr.write(Usage) | |
else: | |
FileName = sys.argv[1] | |
InFile = open(FileName,'rU') | |
# this is set up to insert our file name | |
# match lines starting with center tag, spaces or not, then ![] | |
# capture the text between the [escaped] parentheses | |
OneLineSearch = r"<center> *\!\[\] *\((.+)\).*" | |
OutString = "\centerline{\includegraphics[height=2in]{%s}}" | |
FoundCenter = False | |
DeleteNext = False | |
for RawLine in InFile: | |
Line = RawLine.rstrip() | |
if FoundCenter: | |
## Check if it is a figure tag | |
# If not, we should print out the center tag and this line.. | |
if Line.strip().startswith(r"![]"): | |
# This takes the line, splits on open paren, then cuts off last character (close paren) | |
ImageName = Line.strip().split("(")[1][:-1] | |
print OutString % (ImageName) | |
DeleteNext = True | |
# in this case, we found a center tag in the prior line, | |
# but not the right one, so print it retroactively | |
else: | |
print "<center>\n" + Line | |
FoundCenter = False | |
elif Line.strip().startswith("<center>"): | |
OneLine = re.search(OneLineSearch,Line) | |
if OneLine: | |
ImageName = OneLine.group(1) | |
print OutString % (ImageName) | |
else: | |
FoundCenter = True | |
elif Line.strip().startswith("</center>"): | |
if not DeleteNext: | |
print Line | |
DeleteNext = False | |
else: | |
print Line | |
InFile.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment