如何计算一个字符串的实例并用另一个字符串+当前计数器替换它们?

2024-09-29 10:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉:我是编程新手。我真的很努力让它工作。我想我知道问题是什么,但不知道如何解决。我在代码中使用了这个论坛上的一些回答问题,但这还不够。你知道吗

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

你能告诉我怎么解决我的问题吗?我的剧本写得对吗?你知道吗


Tags: 文件字符串代码textintxtlinesolution
1条回答
网友
1楼 · 发布于 2024-09-29 10:21:03

你很接近,这里是可以做这项工作的代码,希望这能有所帮助:

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'以返回新行。你知道吗

相关问题 更多 >