Python 如何排除空行的行号

Python 如何排除空行的行号,python,tkinter,Python,Tkinter,我最近正在尝试在Tkinter中实现一个额外的特性。我的问题很容易理解。下面我提到了我的代码和XML文件 Data.xml: <?xml version="1.0" ?> <p1:FILE xmlns:p1="http://www.example.org/eHorizon"> <Time nTimestamp="12"> <Test> <Car/>

我最近正在尝试在Tkinter中实现一个额外的特性。我的问题很容易理解。下面我提到了我的代码和XML文件

Data.xml:

<?xml version="1.0" ?>
<p1:FILE xmlns:p1="http://www.example.org/eHorizon">


     <Time nTimestamp="12">
            <Test>
                <Car/>
            </Test>
     </Time>
</p1:FILE>
记事本++中的data.xml:

我想要什么:

我只想在有空行的地方省略行号。因此,每当我使用
sourceline
时,它应该返回行号,不包括所有空格

在上面的代码
print“时间元素的行号为=”,元素列表[0]。sourceline
应该打印答案3(不包括空行),而不是5(包括空行)

我的尝试:

我试着到处找,但没有找到我想要的。坦率地说,到目前为止,我甚至无法思考如何发起。我已经在使用
sourceline
,它只是返回给定的行号,并考虑所有空格


EDIT:我正在使用
sourceline
,因为我正在处理xml元素并使用lxml库提取xml数据

如果你真的想这样做,我看到了两种选择:

删除空行

不带空白行重新创建文件。

跟踪空行 跟踪每个实际源行号之前存在的空行数。从实际源行号中减去该值

# track blanks
blanks_before_line = [0]
with open('data.xml') as f:
    for line in f:
        new_blanks = blanks_before_line[-1]
        if not line.strip():
            new_blanks += 1
        blanks_before_line.append(new_blanks)

# now in your code subtract it
# .....
real_sourceline = ElementsList[0].sourceline
adjusted_sourceline = real_sourceline - blanks_before_line[real_sourceline - 1]
print "The line number of Time element is = ", adjusted_sourceline

我不确定
sourceline
从哪里来,但您的预期输出究竟是什么?@Jkdc我在问题中添加了EDIT<代码>源代码用于在lxml库解析xml文档时提取行号。预期输出是当我在文本框中提取上述给定数据的行号时,
1
应该属于
1行
,而
2
应该属于
2行
。在上面的例子中,它2属于
第3行
“我的问题很容易理解。”实际上,我很难理解你在做什么。您为什么不共享代码(几乎每次在stackoverflow上都应该这样)来显示如何生成tkinter窗口,然后如何获取错误的数据,最后显示您希望获取的确切数据?换句话说,感谢您的回复。我编辑了整个问题。以前我想让问题更简短、更中肯。但细节还不够。我发布了一个直接的答案,但。。。为什么?为什么要删除空行?这个数字有什么用处?我觉得一定有更好的方法来完成你想要的。
# track blanks
blanks_before_line = [0]
with open('data.xml') as f:
    for line in f:
        new_blanks = blanks_before_line[-1]
        if not line.strip():
            new_blanks += 1
        blanks_before_line.append(new_blanks)

# now in your code subtract it
# .....
real_sourceline = ElementsList[0].sourceline
adjusted_sourceline = real_sourceline - blanks_before_line[real_sourceline - 1]
print "The line number of Time element is = ", adjusted_sourceline