如何计算一个字符串的实例并将其替换为另一个字符串+当前计数器?

问题描述 投票:2回答:1

道歉:我是编程新手。老实说,我努力使它工作。我认为我了解问题所在,但不了解如何解决。我在代码中使用了此论坛上的一些已回答问题,但这还不够。

起始点:我有一个txt文件。在此txt文件中,某些行包含特定字符串'<lb n=""/>',而其他行则不包含。以这个为例

<lb n=""/>magna quaestio
<lb n=""/>facile solution
<pb n="5"/>
<lb n=""/>amica responsum

目标:我想每行计算字符串<lb n=""/>行,并将当前计数器填充到字符串中。

因此,运行脚本后,示例应如下所示:

<lb n="1"/>magna quaestio
<lb n="2"/>facile solution
<pb n="5"/>
<lb n="3"/>amica responsum

下面是我脚本的相关部分。

问题:使用脚本时,每个字符串都将替换为总计数器<lb n="464">,而不是当前计数器。

代码:

def replace_text(text):
    lines = text.split("\n")
    i = 0
    for line in lines:
        exp1 = re.compile(r'<lb n=""/>')                            # look for string
        if '<lb n=""/>' in line:                                    # if string in line
            text1 = exp1.sub('<lb n="{}"/>'.format(i), text)        # replace with lb-counter
            i += 1
    return text1

您能告诉我如何解决我的问题吗?我的脚本是否在正确的轨道上?

python regex text-files line-count
1个回答
0
投票

您非常接近,这是代码可以完成的工作,希望对您有所帮助:

with open('1.txt') as f1, open('2.txt', 'w') as f2:
    i = 1
    exp1 = re.compile(r'<lb n=""/>')      # look for string
    for line in f1:             
        if '<lb n=""/>' in line:                                        # if string in line
            new_line = exp1.sub('<lb n="{}"/>'.format(i), line) + '\n'           # replace with lb-counter
            i += 1
            f2.write(new_line)
        else:
            f2.write(line)

基本上,只需从一个文件中读取行并更改str并将该行写入新文件。

我将'/ n'添加到新行的末尾以返回新行。

© www.soinside.com 2019 - 2024. All rights reserved.