【发布时间】:2020-03-20 07:19:16
【问题描述】:
所以我试图从这样的原始文本文件中提取某些值
Number of zero columns: 4
Memory requirement - global matrix: 1571340 solver (totally): 1571340
P1127_VELOCITIES #001000 Step: 59 Iteration: 2 Time: 0.04055 0.0015347
P2243_VELOCITIES #001000 Step: 59 Iteration: 2 Time: 0.04055 0.0017193
P3387_VELOCITIES #001000 Step: 59 Iteration: 2 Time: 0.04055 0.0015347
% of load in interval Step: 59 Iteration: 2 Time: 0.04055 0.0400000 0.0400000
summation % of load in interval Step: 59 Iteration: 2 Time: 0.04055 0.0800000
Number of zero columns: 4
Memory requirement - global matrix: 1571340 solver (totally): 1571340
P1127_VELOCITIES #001000 Step: 59 Iteration: 2 Time: 0.01638 -0.0016876
P2243_VELOCITIES #001000 Step: 59 Iteration: 2 Time: 0.01638 -0.0018896
P3387_VELOCITIES #001000 Step: 59 Iteration: 2 Time: 0.01638 -0.0016876
% of load in interval Step: 59 Iteration: 2 Time: 0.01638 0.0400000 0.0400000
summation % of load in interval Step: 59 Iteration: 2 Time: 0.01638 0.0800000
所以我想用这段代码提取P1127_VELOCITIES:
P1127_positive = re.compile(r'P1127_VELOCITIES #001000 Step: (\d+) Iteration: (\d+) Time: (\d+\.\d+) (\d*\.\d+|-\d*\.\d+)')
P1127_negative = re.compile(r'P1125_VELOCITIES #001000 Step: (\d+) Iteration: (\d+) Time: (\d+\.\d+) (\d*\.\d+|-\d*\.\d+)')
def Extract_Data(filepath, expression_positive, expression_negative, data):
velocity_list = []
time_list = []
#negative_data = []
with open(filepath) as file:
for line in file:
data.extend(expression_positive.findall(line))
with open(filepath) as file:
for line in file:
data.extend(expression_negative.findall(line))
print(data[0])
print(data[1])
for data_tuple in data:
step, iteration, time, velocity = data_tuple
velocity_list.append(float(velocity))
time_list.append(float(time))
return velocity_list, time_list
但是,我想在右端提取所有浮点值,而不是分别提取正负值。正如您在文本文件中看到的,正值有 2 个空格(即Time: 0.04055[space][space]0.0015347,而负值只有 1 个空格(即Time: 0.01638[space]-0.0016876)
有没有办法使用 re.compile 来提取这两个值? (就像我上面的一样,但都提取了)。你会推荐什么表达方式? (即([-+]?\d\.\d+))
干杯!
【问题讨论】:
-
只做
re.findall(r"(?m)P112[57].*\s(-?\d\S+)\s*$",file.read()) -
嗨 ggorlen,我想从一些文本文件中提取速度(P1127、P2243 等),并且我想从中提取所有值。我要提取的一行示例是:
P1127_VELOCITIES #001000 Step: 59 Iteration: 2 Time: 0.02419 -0.0010204 -
@Tan Phan 您面临的具体问题是什么?哪条线是速度?哪个是时间?为什么你需要不同的消极和积极?您不能将它们都提取到一个列表中吗?
标签: regex python-3.x dataframe text-extraction data-extraction