【发布时间】:2016-03-26 21:52:38
【问题描述】:
所以我有一个程序可以推理行文件并将任何错误打印到标准错误。因此,如果我得到如下所示的输入:
line 1 2x 3 4
line 1 2 x3 4
lixe 251 2 3 4 5
line 1 2 3 4
line 251 2 3 4
那么输出应该是这样的:
Error in line 1:
line 1 2x 3 4
^
Error in line 2:
line 1 2 x3 4
^
Error in line 3:
lixe 251 2 3 4 5
^
Error in line 5:
line 251 2 3 4
^
Error in line 6:
line 1 2 3 4 5
^
这就是我的错误检查:
except Exception as e:
for line in lines_file:
print >> sys.stderr, 'Error in line ' + str(line_number) + ":"
print >> sys.stderr, " " * 4 + line,
print >> sys.stderr, " " * (offset + 4) + "^"
sys.exit(1)
但是对于这段代码,输出是这样的:
Error in line 1:
line 1 2 x3 4
^
Error in line 1:
lixe 251 2 3 4 5
^
Error in line 1:
line 1 2 3 4
^
Error in line 1:
line 251 2 3 4
^
Error in line 1:
line 1 2 3 4 5
^
Error in line 1:
line 1 2 3 4 x5
^
而且它只显示一行。那么我怎样才能让它打印出所有的行呢?这是我的 try bock 代码:
for line in lines_file:
line_number = 1
#get offset up to start of coordinates
start = re.compile('\s*line\s*')
m = start.match(line)
offset = m.end()
try:
for i in range(4):
xy = re.compile('\s*([-]?[0-9]{1,3})\s*')
if xy.match(line,offset):
m = xy.match(line,offset)
else:
raise Exception
coordinate = m.group(1)
if int(coordinate) > 250 or int(coordinate) < -250:
raise Exception
offset = m.end()
end = re.compile('\s*$')
if not end.match(line,offset):
raise Exception
except Exception as e:
for line in lines_file:
print >> sys.stderr, 'Error in line ' + str(line_number) + ":"
print >> sys.stderr, " " * 4 + line,
print >> sys.stderr, " " * (offset + 4) + "^"
sys.exit(1)
line_number += 1
offset = 0
p = re.compile('line\s*([-]?[0-9]{1,3})\s*([-]?[0-9]{1,3})\s*([-]?[0-9]{1,3})\s*([-]?[0-9]{1,3})')
m = p.match(line)
x0 = int(m.group(1))
y0 = int(m.group(2))
x1 = int(m.group(3))
y1 = int(m.group(4))
print str(x0), str(y0), str(x1), str(y1)
【问题讨论】:
-
你需要编写一个循环来打印所有内容
-
什么样的循环。你去“for x in line”的地方是for each循环吗?
-
好的,我更新了我的代码以显示我的程序的更多内容。
-
再次更新了我的代码,尝试循环遍历所有行错误,但我仍然无法获得正确的输出。
-
刚刚再次更新了我的代码。现在不止一行,但实际的行不按顺序排列。