Python的`if`语句表现不同取决于执行它的位置?

时间:2017-03-21 03:51:33

标签: python

为什么代码if line and not line[0].isdigit() and line != '\n':在进出项目时表现不同? 我在第88行的项目meltsubtitles中提取了以下代码摘录:

with open('test.txt', 'r', encoding='utf-8') as finput:
    for line in finput:
        if line and not line[0].isdigit() and line != '\n':
            pass
        else:
            print(line)

当我从项目中提取代码并使用text.txt运行它时,打印出来:

1

00:00:03,940 --> 00:00:07,550



2

00:00:09,280 --> 00:00:10,650

但是当我将类似的代码放到我的项目中时,第一个line '1\n'没有打印出来。输出是:

00:00:03,940 --> 00:00:07,550

2
00:00:09,280 --> 00:00:10,650

我的期望是:

1
00:00:03,940 --> 00:00:07,550

2
00:00:09,280 --> 00:00:10,650

line = '1\n'时,我使用pycharm调试并进入关键行if line and not line[0].isdigit() and line != '\n':奇怪地会遇到if语句,而它不应该,但是当我提取代码时,它不会遇到if语句。

test.txt文件是

1
00:00:03,940 --> 00:00:07,550
Horsin' Around is filmed before a live studio audience.

2
00:00:09,280 --> 00:00:10,650
Mondays.

我的项目位于github meltsubtitles第88行。 我正在运行Python 3.5并在win 10中运行。

1 个答案:

答案 0 :(得分:0)

您对类似代码的意义是什么?

我通过代码重写任务:

import logging
logging.basicConfig(level=logging.DEBUG)

def begin_numebr(string=None):
    if string is None:
        return False
    else:
        return string.strip() != '' and string[0].isdigit()

def line_filter(lines):
    return filter(lambda line: begin_numebr(line), lines)

for line in line_filter(open('test.txt')):
    print(line)

def test():
    assert(begin_numebr('')==False)
    assert(begin_numebr(' ')==False)
    assert(begin_numebr('\n')==False)
    assert(begin_numebr('\t')==False)
    assert(begin_numebr('\b')==False)
    assert(begin_numebr()==False)
    assert(begin_numebr('not digit')==False)
    assert(begin_numebr('00not digit')==True)
    print('test done')

    lines = ['001', 'this is']
    logging.debug(line_filter(lines))
    assert(line_filter(lines) == ['001'])

#test()