【发布时间】:2015-04-10 01:15:15
【问题描述】:
这是一个棘手的问题,我已经阅读了很多关于它的帖子,但我无法让它发挥作用。
我有一个大文件。我需要逐行阅读它,一旦我到达"Total is: (any decimal number)" 形式的行,就取这个字符串并将数字保存在一个变量中。如果数字大于 40.0,那么我需要找到 Total 行上方的第四行(例如,如果 Total 行是第 39 行,则此行将是第 35 行)。该行的格式为"(number).(space)(substring)"。最后,我需要将这个子字符串解析出来并对其进行进一步处理。
这是一个输入文件的示例:
many lines that we don't care about
many lines that we don't care about
...
1. Hi45
People: bla bla bla bla bla bla
whitespace
bla bla bla bla bla
Total is: (*here there will be a decimal number*)
bla bla
white space
...
more lines we don't care about
and then more lines and then
again we get
2. How144
People: bla bla bla bla bla bla
whitespace
bla bla bla bla bla
Total is: (*here there will be a decimal number*)
bla bla
white space
我尝试了很多东西,包括使用re.search() 方法从我需要关注的每一行中捕获我需要的内容。
这是我从另一个 stackoverflow 问答中修改的代码:
import re
import linecache
number = ""
higher_line = ""
found_line = ""
with open("filename_with_many_lines.txt") as aFile:
for num, line in enumerate(aFile, 1):
searchObj = re.search(r'(\bTotal\b)(\s)(\w+)(\:)(\s)(\d+.\d+)', line)
if searchObj:
print "this is on line", line
print "this is the line number:", num
var1 = searchObj.group(6)
print var1
if float(var1) > 40.0:
number = num
higher_line = number - 4
print number
print higher_line
found_line = linecache.getline("filename_with_many_lines.txt", higher_line)
print "found the", found_line
预期的输出是:
this is on line Total is: 45.5
this is the line number: 14857
14857
14853
found the 1. Hi145
this is on line Total is: 62.1
this is the line number: 14985
14985
14981
found the 2.How144
【问题讨论】:
-
提供一个示例以及预期的输出。
-
数量不大于40怎么办?
-
“我的一个尝试是部分成功的,因为它给了我所有“Total is”的行,但它并没有得到它们全部。它得到了他们所有,但它没有得到他们所有?你能更具体地说明它是如何分解的吗?
-
顺便说一句,如果文件是在
with语句的标题中打开的,则不需要对文件调用close()。
标签: python regex file line python-2.x