如何在python中使用heading提取文本文件中的特定行并在函数中返回?

2024-04-20 06:01:54 发布

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

我试图提取特定的信息从文本文件中使用的标题文件。在那里每个标题都有不同的标题和相应的内容。我需要从特定的标题中提取内容并在函数中返回它。我尝试了很多方法,但都无法实现

Here is the description of file:

    INTERFACE 2: XYZ =====================================
     bLength            :    0x9 (9 bytes)
     bDescriptorType    :    0x4 Interface
     bInterfaceNumber   :    0x2
     bAlternateSetting  :    0x0
    INTERFACE 2, 1: ABC ==================================
     bLength            :    0x9 (9 bytes)
     bDescriptorType    :    0x4 Interface
     bInterfaceNumber   :    0x2
     bAlternateSetting  :    0x1
     bNumEndpoints      :    0x1
      ENDPOINT 0x1: Isochronous ========================
       bLength          :    0x9 (7 bytes)
       bDescriptorType  :    0x5 Endpoint
       bEndpointAddress :    0x1 OUT

我需要提取像ABC内容,XYZ内容,但不能提取这些信息。你知道吗

我的问题如下: 1) 我们将如何提取具有特定标题的内容,以及如何在某些函数中返回它?你知道吗


Tags: 文件函数信息标题内容bytesinterfaceabc
1条回答
网友
1楼 · 发布于 2024-04-20 06:01:54

不确定这是否是您想要的,但这将为您提供一本包含标题和内容的词典:

content_dict = dict()
heading_line = None
for l in f.readlines():
    # recognize heading lines
    if "======" in l:  # if this doesn't cover, you might need to define a regex
        heading_line = l
        content_dict[heading_line] = dict()
    else:
        field_name = l.split(':')[0].strip()
        field_val = l.split(':')[1].strip()
        content_dict[heading_line][field_name] = field_val

使用上面的内容dict,每个标题都有一个字段字符串值的dict。如果你愿意,你可以从他们那里提取你需要的任何东西。你知道吗

相关问题 更多 >