在python 3.6.3中使用正则表达式我试图提取与特定开始文本和结束文本相关的科学计数法数字。从以下示例数据中:
Not_the_data : REAL[10] (randomtext := doesntapply) := [1.00000000e+000,-2.00000000e000,3.00000000e+000,4.00000000e+000,5.00000000e+000,6.00000000e+000
,7.00000000e+000,8.00000000e-000,9.00000000e+000,1.00000000e+001,1.10000000e+001];
This_data : REAL[2,27] (RADIX := Float) := [3.45982254e-001,9.80374157e-001,8.29904616e-001,1.57800000e+002,4.48320538e-001,6.20533180e+001
,1.80081348e+003,-8.93283653e+000,5.25826037e-001,2.16974407e-001,1.17304848e+002,6.82604387e-002
,3.76116596e-002,6.82604387e-002,3.76116596e-002];
Not_it_either : REAL[72] (randomtext := doesntapply) := [0.00000000e+000,-0.00000000e000,0.00000000e+000,0.00000000e+000,0.00000000e+000,0.00000000e+000];
我只希望“ This_data”集中的数据:
['3.45982254e-001','9.80374157e-001','8.29904616e001','1.57800000e+002','4.48320538e-001','6.20533180e+001','1.80081348e+003','-8.93283653e+000','5.25826037e-001','2.16974407e-001','1.17304848e+002','6.82604387e-002','3.76116596e-002','6.82604387e-002','3.76116596e-002']
如果我不使用环视功能,我可以很容易地获得所有与科学计数法匹配的数字,如下所示:
values = re.findall('(-?[0-9]+.[0-9]+e[+-][0-9]+)',_DATA_,re.DOTALL|re.MULTILINE)
但是,一旦我添加了超前功能:
values = re.findall('(?<=This_data).*?(-?[0-9]+.[0-9]+e[+-][0-9]+)+',_DATA_,re.DOTALL|re.MULTILINE)
除所需集合中的第一个数字以外的所有数字都将落下。我尝试使用正向和负向先行进行多次迭代,并在debugex上进行后向查找,但无济于事。
我的源文件是50k +行,所需的数据集是10-11k行。理想情况下,我希望一次读取文件即可捕获数据集。
如何正确使用超前或后向功能将数据捕获限制为符合格式但仅来自所需“ This_Data”集的数字?
感谢您的帮助!
答案 0 :(得分:0)
您可能更容易一次解析文件,而跳过不符合条件的行。看起来每一行都以分号结尾,因此您可以使用它作为中断解析的一种方式。
import re
PARSING = False
out = []
with open('path/to/file.data') as fp:
for line in fp:
if line.startswith('This_data'):
PARSING = True
if PARSING:
out.append(re.findall('(-?[0-9]+.[0-9]+e[+-][0-9]+)', line)
# check if the line contains a semicolon to stop parsing
if ';' in line:
PARSING = False
# return the results:
out