【发布时间】:2014-06-30 17:32:38
【问题描述】:
假设我有一个正在操作的文本文件。像这样的东西(希望这不是太难以理解):
data_raw = open('my_data_file.dat').read()
matches = re.findall(my_regex, data_raw, re.MULTILINE)
for match in matches:
try:
parse(data_raw, from_=match.start(), to=match.end())
except Exception:
print("Error parsing data starting on line {}".format(what_do_i_put_here))
raise
注意异常处理程序中有一个名为what_do_i_put_here 的变量。我的问题是:如何分配给该名称,以便我的脚本将打印包含我正在尝试使用的“坏区域”开头的 行号?我不介意重新阅读文件,我只是不知道我会做什么......
【问题讨论】:
-
你的正则表达式是否消耗新行?如果没有,你可以逐行查找,然后很容易得到行号。
-
是的,它消耗多行(这就是我使用
re.MULTILINE的原因) -
Re.findall 不返回字符串列表吗?:docs.python.org/2/library/re.html。字符串没有开始或结束方法。
-
不,它返回一个列表
MatchObject实例,请参阅:docs.python.org/2/library/re.html#re.MatchObject