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:])):
CodePudding user response:
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")
CodePudding user response:
You could create a counter where you establish an integer and add 1 to the integer every time you iterate over a line. For example:
file_name = "whatever.txt"
textfile = open(file_name, "r")
line_number = 0 # this integer will store the line number
for line in (textfile):
line_number = 1
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")