首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python替换为内部模式编号

Python替换为内部模式编号
EN

Stack Overflow用户
提问于 2015-09-14 16:29:53
回答 1查看 119关注 0票数 0

我正试图想出一个python脚本来自动为pandoc中的脚注编号。给出这样的输入:

这是只用于测试目的的测试文档。^0这是只用于测试目的的测试文档。这是只用于测试目的的测试文档。^121这是仅用于测试目的的测试文档。 ^0:脚注内容。 ^0:脚注内容。 ^0:脚注内容。

它应该产生这样的产出:

这是只用于测试目的的测试文档。^1这是只用于测试目的的测试文档。这是只用于测试目的的测试文档。^2这是只用于测试目的的测试文档。 ^1:脚注内容。 ^2:脚注内容。 ^3:脚注内容。

我已经能够使基本的功能工作,但我仍然停留在如何涵盖两个脚注在一行的情况。也许循环不应该是基于线的?或者,我是否应该选择某种嵌套循环,以替换模式的第n次出现(据我从this问题中了解,这并不是微不足道的)?

既然我正试图从中学到尽可能多的东西,请随意放弃任何评论或指点,以求进一步改进。谢谢!

下面是我到目前为止掌握的脚本:

代码语言:javascript
运行
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-14 16:45:11

代码语言:javascript
运行
复制
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)

我想你会做你想做的

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32569587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档