pythonregextext-filesline-count

How to count instances of a string and replace them with another string + the current counter?


Apology: I am new to programming. I honestly tried hard to make it work. I think that I understand what the problem is, but not how to solve it. I used some answered questions on this forum in my code, but it wasn't enough.

Initial point: I have a txt-file. In this txt-file some lines contain a specfic string, '<lb n=""/>', while others do not. Take this for example

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

Goal: I want to count the string <lb n=""/> line per line and fill in the current counter into the string.

So after running the script the example should look like this:

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

Below is the relevant part of my script.

Problem: When using my script, every string gets replaced with the total counter <lb n="464"> instead of the current one.

Code:

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

Can you please tell me how to solve my problem? Was I even on the right track with my script?


Solution

  • You are very close, here is the code can do the job, hope this would help:

    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)
    

    Basically, just read line from one file and change the str and write the line to the new file.

    I added '/n' to the end of the new line for returning a new line.