简体   繁体   中英

Finding set of lines after a keyword in python

I have a text file containing:

   X_string
      > data1 : data
      > data2 : data
      > data3 : data
      > data4 : data4_data1
                data4_data2
                data4_data3

   X_string2
      > data1 : data
      > data2 : data
      > data3 : data
      > data4 : data4_1_data1
                data4_1_data2
                data4_1_data3

and so on. The number of data4_data... varies dynamically. But after it ends there is a empty line separating the next similar sequences. I would like to know if there is a method to retrieve data4 found immediately after the match with X_string

That is something like

if string == X_string:
     get_data4()

should return

      > data4 : data4_data1
                data4_data2
                data4_data3

and

 if string == X_string2:
      get data4() 

should return

      > data4 : data4_1_data1
                data4_1_data2
                data4_1_data3

Without re.findall as I need it one data4 per call. But findall gets all the matched pattern at a time, as I have the following in loop

The following function will open a file, scan through it until it finds the search term, then get all the lines beginning with the data4 line until a blank line is reached.

def get_data4(filename, search_term):
    out = []  # will accumulate data4 lines

    with open(filename) as f:
        # find search term
        for line in f:
            if line.strip() == search_term:
                break

        # skip first three data items
        next(f)
        next(f)
        next(f)

        # find data4 (all lines until blank line)
        for line in f:
            if not line.strip():
                break

            out.append(line)

    return ''.join(out)  # concatenate data4 back into a string

Use it like this:

data4 = get_data4('my_data.txt', 'X_string2')
print(data4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM