使用python从文本文件中提取行
问题描述:
我有超过100个.out文件,这些文件是来自统计软件MPlus的输出文件。在每个文件(可以用任何文本编辑器打开),从几百行文字中,有一对夫妇,我很感兴趣线的线条看起来像这些 - >使用python从文本文件中提取行
I ON
K1 -0.247 0.321 -0.769 0.442
K2 0.161 0.232 0.696 0.486
S ON
K1 0.035 0.143 0.247 0.805
K2 -0.123 0.154 -0.799 0.424
Q ON
K1 0.083 0.325 0.255 0.798
K2 0.039 0.229 0.169 0.866
I ON
LABTOTF1 0.014 0.018 0.787 0.431
LABTOTG2 0.011 0.017 0.626 0.532
UGLABTOT 0.001 0.004 0.272 0.786
UMLABTOT 0.098 0.147 0.664 0.507
S ON
LABTOTF1 -0.008 0.019 -0.406 0.684
LABTOTF2 0.000 0.013 -0.018 0.986
UGLABTOT -0.001 0.003 -0.209 0.835
UMLABTOT -0.063 0.115 -0.548 0.584
Q ON
LABTOTF1 -0.013 0.025 -0.532 0.595
LABTOTF2 -0.014 0.023 -0.596 0.551
UGLABTOT 0.007 0.006 1.131 0.258
UMLABTOT -0.489 0.171 -2.859 0.004
数字不断变化,变量(K1,K2,LABTOTF1等)和变量数量通过文件保持不断变化。但是I ON
,S ON
,Q ON
存在于所有文件中。
我想从这些输出文件中提取这些行,并使用python脚本将它们放入单个输出文件中。
至今为止,我的方法包括编写嵌套for循环,既不是有效的,也不是有效的,因为每行文件中行数不断变化。
我的第一个可怕的“测试”在想起来的线I ON
和值(K1 & K2
)尝试使用下面的代码行:
file = open("./my_folder/my_file.out","r")
lines = [line for line in file]
file.close()
collector = []
for i in range(0,len(lines)):
if lines[i] == '\n':
continue
elif "I ON\n" in lines[i]:
collector.append(lines[i])
collector.append(lines[i+1])
collector.append(lines[i+2])
i += 4
continue
什么是提取这些线的最有效和最Python的方式一个文本文件?
编辑:我感兴趣的行是'标题'以及包含变量+值的行。例如。如果我想的I ON
部分,我想从前面的例子中拉下面几行:
I ON
K1 -0.247 0.321 -0.769 0.442
K2 0.161 0.232 0.696 0.486
答
假设这是该文件的结构:
out_lines = []
for line in lines:
if len(line.strip().split()) == 2:
out_lines.append(line)
答
你可以使用正则表达式,如果你想搜索确切的关键结构。以下代码仅适用于一个'.out'文件,并为上述测试数据的每种标题类型生成一个文件。
import re
file_path = 'E:\\' # the path to the folder with the .out file
file_name = 'test.out'
# for multiple files, insert create a loop for the section below.
with open(file_path + file_name, 'r') as f:
line_keys = f.readline()
while line_keys: # If it is not empty
key_search = re.search(' ?[ISQ]\s*ON', line_keys) # search for the key pattern
if key_search is not None: # If a match is found
file_output = line_keys[1:2] + '.txt'
with open(file_path + file_output, 'a') as f_out:
f_out.write(line_keys) # If you repeatedly want the heading of each section
while True: # Read the subsequent lines
lines_data = f.readline()
if lines_data == "\n":
break
if lines_data == "":
break
f_out.write(lines_data)
f_out.write('\n') # to separate the different sections by a blank line
line_keys = f.readline()
对不起,看起来我不清楚我的问题。更新它以显示我有兴趣拉什么线。 –
你可以很容易地扩展我的例子。只需将每行添加到'out_lines',并且如果第二行('if len(line.strip()。split())== 2')的条件为真,则“flush”该行列表并开始新的一个。 –
嗨Shachar,不会工作的原因是因为缺乏特异性。如果文本中有另一行只有两个单词,那么它也会附加到输出变量中。 –