python - 从文本文件中提取 block

标签 python python-3.x

我有一个包含以下格式 block 的文本文件

...some lines before this...
MY TEST MATRIX (ROWS)
 0.5056E+03  0.8687E-03 -0.1202E-02 
 0.5056E+03  0.8687E-03 -0.1202E-02 
MY TEST END
 0.5056E+03  0.8687E-03 -0.1202E-02  
 0.3776E+03  0.8687E-03  0.1975E-04  
STOP
---some lines after this
MY TEST MATRIX (ROWS)
 2E+04  2E+04  0.8687E-03  
 2E+04  2E+04  0.8687E-03
MY TEST END
 0.5056E+03  0.8687E-03 -0.1202E-02 
 0.5056E+03  0.8687E-03 -0.1202E-02 
STOP
---some lines after this
---this repeats in txt file----

文本文件中有很多这样的 block , block 出现在不同的地方。我只想提取出现在 MY TEST MATRIX (ROWS) 和 MY TEST END 之间的值,MY TEST END 和 STOP 到单个数组让我们称它们为 firstvalue[] 和 secondvalue[]。

对我来说,一个 block 是“我的测试矩阵-我的测试结束-停止”

使用此处显示的简单代码,我可以从文本文件中读取一个数据 block 。但是,由于我的文本文件中有重复的 block ,所以我不知道如何从上述两个数组中的每个 block 中捕获数据。

    import os
    import sys
    from math import *
    firstValue = []
    secondValue = []
    checkFirst = False
    checkSecond = False
    filename="r3dmdtr2.txt"
    with open(filename, "r") as infile:

        for line in infile:
            if line.strip().startswith("MY TEST MATRIX (ROWS)"):
                checkFirst = True
            if line.strip().startswith("MY TEST END"):
                checkFirst = False
                checkSecond = True
            if line.strip().startswith("STOP"):
                checkSecond = False  

            if checkFirst:
                firstValue.append(line) 

            if checkSecond:
                secondValue.append(line)          

    print(firstValue)
    print (secondValue)

上面的片段完美地读取了一个数据 block 。我怎样才能解析我的文本文件中的所有重复 block 并将它们作为一个单独的数组附加到我的 firstValue[]

类似于:

firstvalue = [[来自第一个 block 的值],[来自第二个 block 的值],依此类推... secondvalue = [[第一个 block 的值],[secondblock 的值],依此类推...

最佳答案

你可以使用re.findall

>>> import re
>>> data = open('file.txt').read()
>>> blocks = re.findall(r'MY TEST MATRIX \(ROWS\)\s*(.*?)\s+MY TEST END\s*(.*?)\s+STOP', data, re.DOTALL)
>>> first, second = zip(*blocks)
>>> print (first)
('2X+00  2X+00  1X+00  \n 2X+00  2X+00  1K+00', '2P+00  2X+00  1M+00  \n 2X+00  2Z+00  1K+00')
>>> print (second)
('2Y+00  2Y+00  1E+00  \n 2Y+00  2Z+00  1E+00', '2Y+00  2Y+00  1E+00  \n 2Y+00  2Z+00  1E+00')

关于python - 从文本文件中提取 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51597754/

相关文章:

python - 类型错误 : object of type 'generator' has no len()

python - CImg Python 3 绑定(bind)或至少具有可比性的东西?

python - 使用 python argparse 解析嵌套列表

python - 我应该使用 ndb 结构化属性还是单独的模型来限制我的 GAE 查询。基础数据建模问题。

python - pygame-如何使屏幕变暗

python - SyntaxError 无效 token

python - getsizeof() 函数在 Python 2 和 Python 3 中返回不同的输出

python - 如何比较元组列表?

python - 使用元组作为字典键

python - 如何在Python中检查视频是否有声音?