我想制作一个创建脚注的 Python 脚本。这个想法是找到该排序的所有字符串"Some body text.{^}{Some footnote text.}"
并将它们替换为"Some body text.^#"
, where "^#"
是正确的脚注编号。 (我的脚本的另一个部分涉及实际打印文件底部的脚注。)我当前使用的代码是:
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
这将返回匹配的号码。
可以使用任何可调用的,因此您可以使用类来跟踪编号:
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()
run.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)