这个任务就是Python的生成器创建的目的。在
首先,我们将制作一个生成器,它将获取每一行中您感兴趣的内容:def get_interesting_line(file,*searches):
with open(file,'r') as f:
for line in f:
if all(search in line for search in searches):
yield line
# Use it like this:
interesting_lines = get_interesting_line(myfile,':command','started.')
next(interesting_lines)
# Or like this:
for line in get_interesting_line(myfile,':command','started.'):
print(line)
然后,我们将生成另一个生成器,它从任何其他生成器/迭代器返回一个由项和以下项(或者换句话说,前一个项和当前项)组成的元组:
^{pr2}$
现在,我们可以将它们放在一起,并创建另一个生成器,它将根据您的条件输出一个由数据、值、上一时间和当前时间组成的四元组(我们将使用datetime模块将时间存储为datetime对象)。在from datetime import datetime
def get_command_file_delta_t_info(file):
c_lines = get_interesting_line(file,':command','started.')
line_pairs = get_item_pair(c_lines)
for line1, line2 in line_pairs:
value1 = line1.split('command: ')[1].split(' started.')[0]
value2 = line2.split('command: ')[1].split(' started.')[0]
if value1 != value2:
#value changed
year1 = line1.split(' ',1)[0]
year2 = line2.split(' ',1)[0]
#assuming date is MM/DD format:
month1 = line1.split()[1].split('/')[0]
month2 = line2.split()[1].split('/')[0]
day1 = line1.split()[1].split('/')[1]
day2 = line2.split()[1].split('/')[1]
#now hours, minutes, seconds:
hour1 = line1.split()[2].split(':')[0]
hour2 = line2.split()[2].split(':')[0]
minute1 = line1.split()[2].split(':')[1]
minute2 = line2.split()[2].split(':')[1]
second1 = line1.split()[2].split(':')[2]
second2 = line2.split()[2].split(':')[2]
#now create a couple of date time objects for initial and final times
dt_i = datetime(year1, month1, day1, hour1, minute1, second1)
dt_f = datetime(year2, month2, day2, hour2, minute2, second2)
#strip out data
data = line2.split(':command ')[1].split(" " value2)[0]
#finally yield a tuple containing the data you want
yield (data, value2, dt_i, dt_f)
如上所述,此生成器生成以下格式的项目:#create the generator
my_gen = get_command_file_delta_t_info(myfile)
#Get first generated item:
next(my_gen)
#produces:
(data1, value1, dt_i1, dt_f1)
#Now we can get the second item, 3rd, etc:
next(my_gen)
(data2, value2, dt_i2, dt_f2)
#get all the remaining items and do stuff with them:
for item in my_gen:
do_stuff(item)
# note that the first item in the for statement is actually the 3rd
# item that has been generated. the first two were generated in the
# lines above. my_gen does not "start over".
如上所示,生成器是一个iterable对象,当生成器被迭代时(例如,使用next())或在for语句中迭代生成器中的下一个项。在
现在,我们可以对文件数据执行任何操作,包括创建一个函数,以我们想要的格式输出:def print_command_file_delta_t_info(command_file_delta_t_info):
for info in command_file_delta_t_info:
#get the time difference
#time_diff is a datetime.timedelta object
time_diff = info[3] - info [2]
#now print the information you want:
print("{data} {value} : {minutes} minutes".format(data = info[0], value = info[1], minutes = time_diff.total_seconds()/60))