Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading