I want to make a Python script that creates footnotes. The idea is to find all strings of the sort \"Some body text.{^}{Some footnote text.}\"
and replace them with
It seems like a good fit for a closure:
def make_footnote_counter(start=1):
count = [start - 1] # emulate nonlocal keyword
def footnote_counter(match):
count[0] += 1
return "<sup>%d</sup>" % count[0]
return footnote_counter
new_body_text = re.sub(pattern, make_footnote_counter(), text)
A variation and Python-3-only solution:
def make_create_footnote_numbers(start=1):
count = start - 1
def create_footnote_numbers(match):
nonlocal count
count += 1
return "<sup>{}</sup>".format(count)
return create_footnote_numbers
new_body_text = re.sub(pattern, make_create_footnote_numbers(), text)
Any callable can be used, so you could use a class to track the numbering:
class FootnoteNumbers(object):
def __init__(self, start=1):
self.count = start - 1
def __call__(self, match):
self.count += 1
return "<sup>{}</sup>".format(self.count)
new_body_text = re.sub(pattern, FootnoteNumbers(), text)
Now the counter state is contained in the FootnoteNumbers()
instance, and self.count
will be set anew each time you start a re.sub()
run.