匹配文本文件中的字符串块

问题描述

我阅读了多个与我的问题类似的讨论,但找不到可行的解决方案! 我有一个这样的txt文件

blah L1 blah 
**ON**
...(uninteresting)
...(uninteresting)

conf1
...(uninteresting)
...(uninteresting)

port1:   3 blah blah

port2:  8 blah blah

port3:   0 blah blah

port4:   0 blah blah

conf2
...(uninteresting)
...(uninteresting)

port1:   21 blah blah

port2:  18 blah blah

port3:   0 blah blah

port4:   1 blah blah


conf3
...(uninteresting)
...(uninteresting)

port1:   42 blah blah

port2:  38 blah blah

port3:   2 blah blah

port4:   5 blah blah

**ON_2K**
...(uninteresting)
...(uninteresting)

conf1
...(uninteresting)
...(uninteresting)

port1:   3 blah blah

port2:  8 blah blah

port3:   0 blah blah

port4:   0 blah blah

conf2
...(uninteresting)
...(uninteresting)

port1:   21 blah blah

port2:  18 blah blah

port3:   0 blah blah

port4:   1 blah blah


conf3
...(uninteresting)
...(uninteresting)

port1:   42 blah blah

port2:  38 blah blah

port3:   2 blah blah

port4:   5 blah blah

etc. etc.

我想做的是根据不同的配置,用匹配“port#: 42 blah blah”的那些行中写的数字填充一些不同的pandas数据帧。 所以总共有 2 个不同的 df:

df_L1_ON = pd.DataFrame(index =['conf1','conf2','conf3'],columns =['PORT1','PORT2','PORT3','PORT4'])

df_L1_ON_2k = pd.DataFrame(index =['conf1','PORT4'])

一般来说,我过去常常在文件中查找匹配项并获得我想要的部分:

with open("file") as g:
    for line in g:
        if " " in line: continue
        if " port1 " in line:
             vals = line.split()
             x.append(float(vals[2]))

在这种情况下我需要更深入的解析,因为我需要得到一个嵌套的值,id est:

  1. 找到“开”

  2. 在随后的“conf#”行中搜索

  3. 在后续行中搜索“port#” & 拆分行 & 附加到正确的 df 索引

这必须为每个 conf 完成,每个端口都用于“ON”和“ON_2K”。 我知道这是一个很大的挑战,但我感谢任何建议。我谈到了 python,但是(正如标题所暗示的那样)如果你在 bash 中有更简单的方法,请仍然回答! 谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)