Skip to content

Instantly share code, notes, and snippets.

@jsonbecker
Last active December 9, 2015 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jsonbecker/4342554 to your computer and use it in GitHub Desktop.
Save jsonbecker/4342554 to your computer and use it in GitHub Desktop.
WP-Footnotes to Markdown footnotes.
from sys import argv
import re
name, file_path = argv
p = re.compile(r"[\s]\(\((.*?[)]{0,1})\)\)[\s]{0,1}")
# The tricky part here is to match all text between (()), including as many as
# one set of (), which may even terminate ))). The {0,1} captures as many as
# one ). The trailing space is there because I often surrounded the (()) with
# a space to make it clear in the Wordpress editor.
# file_path = str(raw_input('File Name >'))
text = open(file_path).read()
footnoteMatches = p.finditer(text)
coordinates = []
footnotes = []
# Print span of matches
for match in footnoteMatches:
coordinates.append(match.span())
# Capture only group(1) so you get the content of the footnote, not the whole
# pattern which includes the parenthesis delimiter.
footnotes.append(match.group(1))
newText = []
for i in range(0, len(coordinates)):
if i == 0:
newText.append(''.join(text[:coordinates[i][0]] +
' [^{}]').format(i + 1))
elif i < len(coordinates) - 1 :
newText.append(''.join(text[coordinates[i-1][1]:coordinates[i][0]] +
' [^{}]').format(i + 1))
else:
newText.append(''.join(text[coordinates[i-1][1]:coordinates[i][0]] +
' [^{}]').format(i + 1))
# Accounts for text after the last footnote which only runs once.
newText.append(text[coordinates[i][1]:]+'\n')
endNotes = []
for j in range(0, len(footnotes)):
insertList = ''.join(['\n','[^{}]: ', footnotes[j], '\n']).format(j + 1)
endNotes.append(insertList)
newText = ''.join(newText) + '\n' + ''.join(endNotes)
newFile = open(file_path, 'w')
newFile.truncate()
newFile.write(newText)
newFile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment