Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renumbering line by line

Tags:

python

I have an input text which looks like this:

word77 text text bla66 word78 text bla67
text bla68 word79 text bla69 word80 text
bla77 word81 text bla78 word92 text bla79 word99

I have to renumber word and bla from 1, in each line.

I can renumber the whole input which looks like this:

word1 text text bla1 word2 text bla2
text bla3 word3 text bla4 word4 text
bla5 word5 text bla6 word6 text bla7 word7

The code for the above:

import re
def replace(m): global i; i+=1; return str(i);
fp = open('input.txt', 'r').read()
i = 0
fp = re.sub(r'(?<=word)(\d+)', replace, fp)
i = 0
fp = re.sub(r'(?<=bla)(\d+)', replace, fp)
#open('sample.txt', 'wb').write(fp)
print fp

Ideally, the result should look like this:

word1 text text bla1 word2 text bla2
text bla1 word1 text bla2 word2 text
bla1 word2 text bla3 word3 text bla4 word4
like image 424
Lajos N Avatar asked Apr 11 '20 08:04

Lajos N


1 Answers

You operate on the whole file at once (fp.read()) - you need to do it line-wise:

with open("input.txt","w") as f:
    f.write("""word77 text text bla66 word78 text bla67
text bla68 word79 text bla69 word80 text
bla77 word81 text bla78 word92 text bla79 word99""")

import re

i = 0

def replace(m): 
    global i 
    i+=1
    return str(i)

with open('input.txt') as fp, open("output.txt","w") as out:
    # read only one line of the file and apply the transformations
    for line in fp:
        i = 0
        l = re.sub(r'(?<=word)(\d+)', replace, line)
        i = 0
        l = re.sub(r'(?<=bla)(\d+)', replace, l)
        out.write(l)

with open("output.txt") as f:
    print(f.read())

Output:

word1 text text bla1 word2 text bla2
text bla1 word1 text bla2 word2 text
bla1 word1 text bla2 word2 text bla3 word3
like image 97
Patrick Artner Avatar answered Oct 19 '22 16:10

Patrick Artner