解析此文件以访问末尾以制表符分隔的表的最佳方法是什么?

2024-04-24 15:53:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有大约15000个以下格式的文本文件(下载示例如下):

https://easyupload.io/res1so

我感兴趣的部分是末尾的表格,它看起来像:

 1     1   GLY       HA2   H      3.55        .     2
 2     1   GLY       HA3   H      3.76        .     2
 3     2   VAL       H     H      8.52        .     1
 4     2   VAL       HA    H      4.20        .     1
 5     2   VAL       HB    H      2.02        .     1

我没有很多解析文件的经验,但我想这里的很多人都会。我可以得到一些关于如何以编程方式提取文件的这一部分的建议吗

例如,是否有一种仅在两行之间读取文件的方法:

_Chem_shift_ambiguity_code

_stop

最好的方法是使用正则表达式使用readline()方法搜索每一行,直到找到合适的部分,然后切换“开启”某个连续将行附加到数据帧的选项吗

提前谢谢你


1条回答
网友
1楼 · 发布于 2024-04-24 15:53:05

这种解析的一种简单方法是使用布尔变量记录我们是否在要处理的块内,并在找到关键字时切换它:

with open(filename) as fd:
    inblock = False
    for line in fd:
        if inblock:                        # we are inside the block here
            if len(line.strip()) == 0:
                continue                   # ignore blank lines inside block
            elif 'stop_' in line:
                inblock = False
                break                      # stop processing the file
            else:                          # ok, we can process that line
                ...
        else:                              # still waiting for the initial keyword
            if '_Chem_shift_ambiguity_code':
                inblock = True             # ok we have found the beginning of the block

相关问题 更多 >