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

2024-10-01 09:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以下格式的文件。在

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新手,任何帮助都将非常感谢。在


Tags: 文件to函数from状态格式status时间
3条回答

我建议您在python文档中有一个read,特别是time module和函数strptime,它们可以将时间的文本表示解析为编程表示。在

以您在问题中编写的方式调用returnstatus肯定会失败,您可能需要使用时间的字符串表示(即“15/07/2010 15:10:01”)或通过传递时间模块中定义的一种数据类型来调用它。在

编辑:显然,如果传入一个字符串时间,那么在文件中查找它就容易得多:

if substring in line:
 # do stuff
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

这有道理吗?或者你想让我解释一下吗?在

编辑

你刚才说的是真的吗?在

date matches and time is less than the time in the function call

换句话说,如果调用return_status( 16/07/2010, <some.time> ),会发生什么?你应该下线吗?在

另一个编辑

我对它进行了编辑,以便进行合理的datetime比较。我想你已经错误地理解了这个不等式:我们循环遍历文件中的行,直到我们希望获取的日期之后的第一行。一旦这个测试失败,line是所需日期之后的第一行,因此它的from值就是我们请求时的状态。您应该使用datetime.datetime调用函数。在

基本上,您需要做的是从日志中提取日期和时间,并将其转换为易于比较的格式。输入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)

相关问题 更多 >