11

我想制作一个创建脚注的 Python 脚本。这个想法是找到所有排序的字符串"Some body text.{^}{Some footnote text.}"并将它们替换为"Some body text.^#",其中"^#"是正确的脚注编号。(我脚本的另一部分处理实际打印出文件底部的脚注。)我为此使用的当前代码是:

pattern = r"\{\^\}\{(.*?)\}"
i = 0
def create_footnote_numbers(match):
   global i
   i += 1
   return "<sup>"+str(i)+"</sup>"

new_body_text = re.sub(pattern, create_footnote_numbers, text)

i这很好用,但是必须在函数外部声明一个变量()create_footnote_numbers然后必须在该函数内部调用它似乎很奇怪。我原以为里面会有一些东西re可以返回比赛的号码。

4

3 回答 3

14

可以使用任何可调用对象,因此您可以使用一个类来跟踪编号:

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)

现在计数器状态包含在FootnoteNumbers()实例中,self.count每次开始re.sub()运行时都会重新设置。

于 2013-05-26T17:12:11.383 回答
6

这似乎很适合关闭

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)
于 2013-05-26T17:52:26.063 回答
4

变体和仅限 Python-3 的解决方案:

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)
于 2013-05-26T17:56:43.570 回答