【问题标题】:Parse data from several equally structured blocks of a text file in python在 python 中从文本文件的几个相同结构的块中解析数据
【发布时间】:2019-04-28 22:09:57
【问题描述】:

我有一个文本文件,其中包含几个这样的文本块:

Module Resistor_SMD:R_0402_1005Metric (layer B.Cu) (tedit 5B301BBD) (tstamp 5CC0A687)
    (at 120.316179 97.92138 90)
    (descr "Resistor SMD 0402 (1005 Metric), square (rectangular) end terminal, IPC_7351 nominal, (Body size source: http://www.tortai-tech.com/upload/download/2011102023233369053.pdf), generated with kicad-footprint-generator")
    (tags resistor)
    (path /610532D4)
    (attr smd)
    (fp_text reference R59 (at 0 1.17 90) (layer B.SilkS)

我想提取以下内容: 120.316179, 97.92138 90 and R59

并将其存储在某个地方...

然后,我想取出那组订单项,并根据前两个数字的值丢弃一些......它们是 XY 坐标。

然后,将其写入列表。

如何使用正则表达式做到这一点? 我正在加载文件并尝试关注 here,但我在添加 pandas 库时迷失了方向。

【问题讨论】:

    标签: python regex list dataframe parsing


    【解决方案1】:

    IMO 你不需要re 来完成这项任务。您可以遍历文件的行,并根据'(at ''fp_text reference' 等信号字符串,填写所有电阻数据的列表,例如:

    with open('textfile.txt') as f:
        data = []
        row = []
        for line in f:
            if row:
                if '(fp_text ref' in line.strip():
                    row.append(line.strip().split()[2])
                    data.append(row)
                    row = []
            else:
                if '(at ' in line.strip():
                    row = line.strip()[:-1].split()[1:4]
    
    print(data)
    
    # [['120.316179', '97.92138', '90', 'R59']]
    

    如果你想从这个数据中得到一个 pandas 数据框:

    import pandas as pd 
    df = pd.DataFrame(data, columns=['x', 'y', 'z', 'R'])
    print(df)
    
    #             x         y   z    R                            
    # 0  120.316179  97.92138  90  R59
    

    【讨论】:

    • Woooooorrrrrdddd... 这就是我要说的
    【解决方案2】:

    This RegEx 可能会帮助您捕获您想要的三个字符串:

    ([\d]+\.[\d]{5,}|R[0-9]+)
    
    • 有两个使用|(OR)连接的简单模式:

      • 左边的那个 ([\d]+\.[\d]{5,}) 检查你想要的浮点数,浮点部分的边界为 5+,并且
      • 右侧的 (R[0-9]+) 具有左侧 R 边界。
    • 您可以随意更改这些边界,然后使用 $1 调用捕获的输出并进行编码。

    • 如有必要,您可以使用 \ 转义语言特定的元字符,例如 .

    【讨论】:

    • 如何保存在 df 中?因为 R9 出现在与 XY 坐标不同的行上
    • 谢谢... re 库仍然让我感到困惑,所以这有帮助!
    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多