Search code examples
pythonfileif-statementline

More than two similar lines in a row fits me


I've got the .txt file like this within:

....

Crista

7:3

2:0

Wiki

4:1

6:2

3:2

6:8

Pope

5:2

0:1


....

Code to find all lines with digits and append it to list:

pp=open('mine.txt')
ll=[]

for line in pp:
    line = line.rstrip()
    if re.findall('^\d{1}:\d{1}', line):
        digits=line
        ll.append(digits)

My output:

ll=['7:3', '2:0', '4:1', '6:2', '3:2', '6:8', '5:2', '0:1']

If there's more than two lines with digits in a row I don't need them in the list

So my desired output is:

ll=['7:3', '2:0', '4:1', '6:2', '5:2', '0:1']

How can I get it?


Solution

  • Try this :

    import re
    pp=open('mine.txt')
    ll=[]
    
    count = 0
    for line in pp:
        line = line.rstrip()
        print(line)
        if re.findall('^\d{1}:\d{1}', line):
            if count < 2 :
                digits=line
                ll.append(digits)
            count += 1
        elif line != "" :
            count = 0
    print ( ll )