使用Python读取和比较文件中的行

0 投票
6 回答
2232 浏览
提问于 2025-04-16 02:17

我有一个文件,里面的格式是这样的。

15/07/2010 14:14:13 changed_status_from_Offline_to_Available
15/07/2010 15:01:09 changed_status_from_Available_to_Offline
15/07/2010 15:15:35 changed_status_from_Offline_to_Away became_idle
15/07/2010 15:16:29 changed_status_from_Away_to_Available became_unidle
15/07/2010 15:45:40 changed_status_from_Available_to_Away became_idle
15/07/2010 16:05:40 changed_status_from_Away_to_Available became_unidle
15/07/2010 16:51:39 changed_status_from_Available_to_Offline
20/07/2010 13:07:26 changed_status_from_Offline_to_Available

我需要在Python里写一个函数,这个函数有两个参数:日期和时间。它应该读取这个文件,并且如果日期匹配且时间早于函数调用中的时间,就返回第二个状态。也就是说,

假设我调用这个函数:returnstatus(15/07/2010, 15:10:01)。 这个函数应该去文件里查找,并返回那一天那时用户的状态,在这个例子中是“离线”。

我还是个Python新手,任何帮助都非常感谢。

6 个回答

0

我建议你去看看Python的官方文档,特别是关于时间模块和其中的strptime函数,这个函数可以把时间的文本表示转换成程序能理解的格式。

你在问题中写的那种方式调用returnstatus肯定会失败,你应该用时间的字符串表示来调用它(比如说 "15/07/2010 15:10:01"),或者传入时间模块中定义的某种数据类型。

补充一下:显然,如果你传入的是字符串格式的时间,那么在文件中找到它会简单得多:

if substring in line:
 # do stuff
1
import datetime
import time

def lines( path_to_file ):
    '''Open path_to_file and read the lines one at a time, yielding tuples
    ( date of line, time of line, status before line )'''
    with open( path_to_file ) as theFile:
        for line in theFile:
            line = line.rsplit( " ", 1 )
            yield ( 
                datetime.datetime.strptime( line[ 0 ], "%d/%m/%Y %H:%M:%S" ),
                line[ 1 ].split( "_" )[ 3 ]
            )

def return_status( statDate ):
    for lineDate, lineStatus in lines( path_to_file ):
        if statDate > lineDate:
            continue
        return lineStatus

这样说清楚了吗?还是你想让我解释一下某些部分?

编辑

你是指你上面说的那些话吗?

日期匹配,并且时间小于函数调用中的时间

换句话说,如果你调用 return_status( 16/07/2010, <some.time> ),应该得到“离线”吗?

另一个编辑

我已经修改了代码,使其能进行合理的 datetime 比较。我觉得你可能把不等式看反了:我们会遍历文件中的每一行,直到找到我们想要获取的日期之后的第一行(只要 statDate > lineDate 就继续读取)。一旦这个测试不成立,line 就是我们想要的日期之后的第一行,所以它的 from 值就是我们请求时的状态。你应该用 datetime.datetime 来调用这个函数。

-1

基本上,你需要做的就是把日志中的日期和时间提取出来,转换成一种容易比较的格式。可以使用 datetime 这个工具。

import datetime

def getStatus(log_list, dt, tm):
 #filter the list
 log_list = [a_log_entry for a_log_entry in log_list if a_log_entry[0] == dt and a_log_entry[1] <= tm]

    #sort it
 log_list.sort(cmp=lambda x,y: cmp(x[1], y[1]))
 if log_list is []:
     return 'No status available for this day and time.'

    #pull out the status
 status_to_return = log_list[-1][2].split('_')[-1].strip()

 return status_to_return

if __name__ == '__main__':
 in_file = open('a.log', 'rU')
 a_list = []

 for line in in_file:
  if line.strip() is not '': #handle whitespace
   a_list.append(line.split(' '))

 #convert string dates and times to datetime objects
 a_list = [ [datetime.datetime.strptime(el[0], '%d/%m/%Y'),
    datetime.datetime.strptime(el[1], '%H:%M:%S'), 
    el[2]] for el in a_list]


 a_date = datetime.datetime(2010, 7, 15)
 a_time = datetime.datetime(1900, 1, 1, 16, 1, 0)
 print getStatus(a_list, a_date, a_time)

撰写回答