为什么代码if line and not line[0].isdigit() and line != 'n':
在项目内外的行为不同?我从我的项目 meltsubtitle 的第 88 行中摘录了以下代码:
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 '1n'
没有打印出来。输出为:
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 = '1n'
时,我使用 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 melt字幕第 88 行。 我正在运行Python 3.5和win 10。
你对类似代码是什么意思?
我通过代码重写任务:
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()