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

时间:2019-02-16 13:42:42

标签: python python-2.7

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

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)我们如何提取具有特定标题的内容以及如何在某些函数中返回它?

1 个答案:

答案 0 :(得分:0)

不确定这是否是您想要的,但这将为您提供带有标题和内容的字典:

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

使用上面的content_dict,对于每个标题,您都有一个字段字符串值的字典。如果您愿意,可以从他们中提取所需的任何内容。