我正试图想出一个python脚本来自动为pandoc中的脚注编号。给出这样的输入:
这是只用于测试目的的测试文档。^0这是只用于测试目的的测试文档。这是只用于测试目的的测试文档。^121这是仅用于测试目的的测试文档。 ^0:脚注内容。 ^0:脚注内容。 ^0:脚注内容。
它应该产生这样的产出:
这是只用于测试目的的测试文档。^1这是只用于测试目的的测试文档。这是只用于测试目的的测试文档。^2这是只用于测试目的的测试文档。 ^1:脚注内容。 ^2:脚注内容。 ^3:脚注内容。
我已经能够使基本的功能工作,但我仍然停留在如何涵盖两个脚注在一行的情况。也许循环不应该是基于线的?或者,我是否应该选择某种嵌套循环,以替换模式的第n次出现(据我从this问题中了解,这并不是微不足道的)?
既然我正试图从中学到尽可能多的东西,请随意放弃任何评论或指点,以求进一步改进。谢谢!
下面是我到目前为止掌握的脚本:
import re
from sys import argv
script, first = argv
i=0
n=0
buff = ''
# open the file specified through the first argument
f = open(first, 'rU')
for line in f:
if re.search(r'\[\^[0-9]+\]:', line):
i += 1
line2 = re.sub(r'\[\^[0-9]+\]:', '[^' + str(i) + ']:', line)
buff += line2
elif re.search(r'\[\^[0-9]+\]', line):
n += 1
line3 = re.sub(r'\[\^[0-9]+\]', '[^' + str(n) + ']', line)
buff += line3
else:
buff += line
print buff
f.close()
发布于 2015-09-14 16:45:11
my_text="""This is a testing document for testing purposes only.[^0] This is a testing document for testing purposes only. This is a testing document for testing purposes only.[^121][^5] This is a testing document for testing purposes only.
[^0]: Footnote contents.
[^0]: Footnote contents.
[^0]: Footnote contents."""
num_notes = len(re.findall("\[\^\d+\]",my_text))
i = -1
def do_sub(m):
global i
i+=1
return "[^%d]"%(i if i < num_notes//2 else i-num_notes//2)
re.sub("\[\^\d+\]",do_sub,my_text)
我想你会做你想做的
https://stackoverflow.com/questions/32569587
复制相似问题