【发布时间】:2019-06-19 07:04:21
【问题描述】:
我正在编写一个代码来从一个很大的Source.txt 文件中提取一些有用的东西。
我的源测试文件示例如下:
Test case AAA
Current Parameters:
Some unique param : 1
Some unique param : 2
Some unique param : 3
Some unique param : 4
*A line of rubbish*
*Another line of rubbish*
*Yet another line of rubbish*
*More and more rubbish*
Test AAA PASS
Test case BBB
Current Parameters:
Some unique param : A
Some unique param : B
Some unique param : C
Some unique param : D
*A line of rubbish*
*Another line of rubbish*
*Yet another line of rubbish*
*More and more rubbish*
Test BBB PASS
现在我正在编写代码以仅提取 Test case 和 Current Parameters:
processed = []
def main():
source_file = open("Source.txt","r") #Open the raw trace file in read mode
if source_file.mode == "r":
contents = source_file.readlines() #Read the contents of the file
processed_contents = _process_content(contents)
output_file = open("Output.txt","w")
output_file.writelines(processed_contents)
pass
def _process_content(contents):
for raw_lines in contents:
if "Test case" in raw_lines:
processed.append(raw_lines)
elif "Current Parameters" in raw_lines:
processed.append(raw_lines)
#I am stuck here
elif "PASS" in raw_lines or "FAIL" in raw_lines:
processed.append(raw_lines)
processed.append("\n")
return processed
#def _process_parameters():
if __name__ == '__main__':
main()
在Current Parameters 行之后,我想获取每一个Some unique param,这些Some unique param 并不总是相同,并附加到processed 列表中,这样它也会在我的Output.txt 中注明
我想要的输出是:
Test case AAA
Current Parameters:
Some unique param : 1
Some unique param : 2
Some unique param : 3
Some unique param : 4
Test AAA PASS
Test case BBB
Current Parameters:
Some unique param : A
Some unique param : B
Some unique param : C
Some unique param : D
Test BBB PASS
如果你看到了,我想删除所有垃圾行。请注意,我的Source.txt 中有很多垃圾。我不知道如何从那里转到下一个raw_lines。感谢您的帮助。
【问题讨论】:
-
@Adam.Er8,很好。但我不知道如何继续到 Param 1 行
-
为什么
elif "Param" in raw_lines不起作用?它是否也捕获了一些垃圾? -
好的,我忘了说,raw_lines 中的 Param 并不总是包含单词 Param。现在将编辑问题
-
好的,这些是
Current Parameters:之后唯一的缩进行吗?因为我们可以做的是每次遇到Current Parameters:时标记一个flag,然后将所有缩进的行都添加进去,当我们找到没有缩进的行时,将flag取下并返回正常模式 -
刚刚编辑了问题,我的参数将是唯一的,并且名称不同。很抱歉造成混乱