如何找到发生某些事情的行号?

How to find the line number in which something occurs?

我试图创建一个程序,它告诉我在给定的文本中是否有 2 个相同的相邻单词以及文本文件中发生这种情况的位置(行和单词编号)。到目前为止,我已经能够确定哪个字号,但似乎无法弄清楚它发生在哪一行。有人能帮帮我吗?到目前为止,在错误/无错误旁边,我能够得到单词编号,但如果我也能得到行号。


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

为什么不在外循环中再次使用 enumerate

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")

您可以创建一个计数器,在其中建立一个整数,并在每次迭代一行时将整数加 1。例如:

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")