【问题标题】:How can I extract data from a line under a header in a text file如何从文本文件标题下的行中提取数据
【发布时间】:2021-03-20 06:47:27
【问题描述】:

我有一个文本文件,我需要从中提取某些数据。我需要的数据将出现在以“No.”开头的标题下。所以我知道在搜索文件时要查找什么,并且可以拆分和打印每个标题。但是,我想提取以“否”开头的数据的下一行的数据。我也不能使用正则表达式。我怎样才能做到这一点?我能够使用下面的代码成功地找到文件中的每个标题,但如前所述,我想获得下一行。

with open(path, 'r') as f:
    for line in f:
        if KEYWORD in line:
            data = line.split()
            print(data)

打印出标题:

['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']

文本文件示例

Internet Protocol Version 4, Src: 192.168.1.180, Dst: 239.255.255.250
    0100 .... = Version: 4
    .... 0101 = Header Length: 20 bytes (5)
    Differentiated Services Field: 0x00 (DSCP: CS0, ECN: Not-ECT)
    Total Length: 358
    Identification: 0xfe2a (65066)
    Flags: 0x4000, Don't fragment
    Time to live: 4
    Protocol: UDP (17)
    Header checksum: 0xc505 [validation disabled]
    [Header checksum status: Unverified]
    Source: 192.168.1.180
    Destination: 239.255.255.250
User Datagram Protocol, Src Port: 35064, Dst Port: 1900
Simple Service Discovery Protocol

No.     Time           Source                Destination           Protocol Length Info
      2 0.307821       192.168.1.180         239.255.255.250       SSDP     422    NOTIFY * HTTP/1.1 

【问题讨论】:

    标签: python file parsing


    【解决方案1】:

    如果您尝试尽可能少地更改您的代码,那么您可以这样做:

    is_next_line_needed = False
    with open(path, 'r') as f:
        for line in f:
            if KEYWORD in line:
                is_next_line_needed = True
            if is_next_line_needed == True:
                data = line.split()
                print(data)
                is_next_line_needed = False
    

    【讨论】:

      【解决方案2】:

      只有下一行。

      KEYWORD_check = False
      with open(path, 'r') as f:
          for line in f:
              if KEYWORD_check:
                  data = line.split()
                  print(data)
                  break
              if KEYWORD in line:
                  KEYWORD_check = True
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-11
        • 1970-01-01
        • 2018-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多