Search code examples
pythonziptext-filesenumerate

How to find the line number in which something occurs?


I was trying to create a program which tells me in a given text if there are 2 adjacent words which are the same and where in the text file does this happen( line and word number). So far I have been able to determine which word number but can't seem to figure out which line it happens in. Would anyone be able to give me a hand please? So far, next to the Error/ No Error, I am able to get the word number but if I could just get the line number as well.


for line in (textfile):
    for x, y in enumerate(zip(line.split(), line.split()[1:])):

Solution

  • Why don't you simply use enumerate again in the outer loop?

    for line_number, line in enumerate(textfile):
        for x, y in enumerate(zip(line.split(), line.split()[1:])):
            if(x,y)==(y,x):
                print(line_number,x,y,"Error")
            else:
                print(line_number,x,y,"No error")