2

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

初始点:我有一个 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

你能告诉我如何解决我的问题吗?我的剧本是否走在了正确的轨道上?

4

1 回答 1

1

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

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”以返回新行。

于 2019-12-15T12:59:45.093 回答