要将此From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 格式的line找到再把09提取出来
name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
d={}
for line in handle:
rline=line.rstrip()
if rline.startswith('From'):
import re
y=re.findall('[0-9]+',rline)
print(y[1])
可是输出是
['5', '09', '14', '16', '2008']
[]
['4', '18', '10', '48', '2008']
[]
['4', '16', '10', '39', '2008']
[]
['4', '15', '46', '24', '2008']
[]
等等
为什么会有空行而致使执行不了y[1],会有traceback, list index out of range。
取值之前判断y的长度是否符合预期
可设置断点调试查看具体情况
你在倒数第二行加上:
if len(y) == 0:
continue