def get_nos(key): start_id = None nos = [] with open('a.txt', 'r') as file: for line in file.readlines(): line_list = line.split(' ') id = line_list[0] no = line_list[1] if line.find(key) > 0: start_id = id nos.append(no) continue if start_id and id != start_id: nos.append(no) return nos print get_nos('flag')
import re with open('file.txt', 'r') as file: flag_num = 0 list_id = [] for line in file.readlines(): if 'flag' in line: flag_num = re.search('(\d+)\s+.*', line).group(1) list_id.append(re.search('\d+\s+(\d+)\s+.*', line).group(1)) continue if not flag_num: continue list_id.append(re.search('\d+\s+(\d+)\s+.*', line).group(1)) target = re.search('{0}\s+.*'.format(flag_num), line) if target: print list_id[:-1] break
输出结果: