【发布时间】:2017-06-16 12:11:57
【问题描述】:
我有一个程序可以告诉我今天谁过生日。
我的姓名和生日存储在一个名为 data.txt 的文本文件中。
以下是 data.txt 的示例:
Master 13/12
Monkey 16/06
Michael 16/06
mike 01/05
Minita 24/06
Mom 12/06
这是程序:
from __future__ import print_function
import time
logic = time.strftime("%d/%m")
err_occur = []
pattern = re.compile(logic, re.IGNORECASE)
try:
with open ('data.txt', 'rt') as in_file:
for linenum, line in enumerate(in_file):
if pattern.search(line) != None:
err_occur.append((linenum, line.rstrip('\n')))
for linenum, line in err_occur:
print("Line ", linenum, ": ", line, sep='')
except IOError:
print ("data.txt Not found")
如果我运行这个程序并且今天的日期是 16/06,它的输出应该是
Line 3: Monkey 16/06
Line 4: Michael 16/06
但是它显示给我的输出只是
Line 3: Monkey 16/06
我猜for...in 语句无效?
他们不应该循环工作吗?
我学习python才几天。我还没有完全理解迭代器。因此,如果您能用外行的方式解释我的错误,那将非常有帮助。
编辑-感谢@zwer 指出我的错误,感谢@Coldspeed 提供更有效的解决方案。
【问题讨论】:
标签: python regex python-2.7 iterator