Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何实现获取最新位置_Python - Fatal编程技术网

Python:如何实现获取最新位置

Python:如何实现获取最新位置,python,Python,目标:- 我需要用下面的输入解析一个文件,并在状态为approved且builddate为latest时获取最新(builddate时间戳应为latest)位置。我提供了示例输入和输出,我有perl中的代码,这是python的新代码,请建议如何在python中实现 INPUT:- Build: M1234BAAAANAAW9321.1 Location: \\dreyers\builds468\INTEGRATION\M1234BAAAANAA9321.1 Comm

目标:- 我需要用下面的输入解析一个文件,并在状态为approved且builddate为latest时获取最新(builddate时间戳应为latest)位置。我提供了示例输入和输出,我有perl中的代码,这是python的新代码,请建议如何在python中实现

INPUT:-
Build:          M1234BAAAANAAW9321.1
Location:       \\dreyers\builds468\INTEGRATION\M1234BAAAANAA9321.1
Comments:       Build completed, labeled, and marked for retention.
Status:         Approved
BuildDate:      10/25/2012 12:51:25


Build:          M1234BAAAANAAW9321.2
Location:       \\crmbld01\Builds\FAILED\M1234BAAAANAA9321.2
Comments:       The build is currently in a failed status.
Status:         Failed
BuildDate:      10/25/2012 19:37:17


Build:          M1234BAAAANAAW9321.3
Location:       \\freeze\builds427\INTEGRATION\M1234BAAAANAA9321.3
Comments:       Build completed, labeled, and marked for retention.
Status:         Approved
BuildDate:      10/25/2012 19:43:28

OUTPUT:-\\freeze\builds427\INTEGRATION\M1234BAAAANAA9321.3
下面是实现的perl代码,我是python新手,请建议如何对该代码进行python化

$ echo 'Build:          M1234BAAAANAAW9321.1
Location:       \\dreyers\builds468\INTEGRATION\M1234BAAAANAAW9321.1
Comments:       Build completed, labeled, and marked for retention.
Status:         Approved
BuildDate:      10/25/2012 12:51:25


Build:          M1234BAAAANAAW9321.2
Location:       \\crmbld01\Builds\FAILED\M1234BAAAANAAW9321.2
Comments:       The build is currently in a failed status.
Status:         Failed
BuildDate:      10/25/2012 19:37:17


Build:          M1234BAAAANAAW9321.3
Location:       \\freeze\builds427\INTEGRATION\M1234BAAAANAAW9321.3
Comments:       Build completed, labeled, and marked for retention.
Status:         Approved
BuildDate:      10/25/2012 19:43:28
' | perl -e'

local $/ = "";
my ( $build_date, $location );
while ( <> ) {
next unless /status:\s+approved/i;
my $date = sprintf "%04d%02d%02d%02d%02d%02d", ( /builddate:\s+(\d
++)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)/i )[ 2, 0, 1, 3, 4, 5 ];
if ( !defined $build_date || $build_date lt $date ) {
    ( $build_date, $location ) = ( $date, /location:\s+(.+)/i );
    }                                                           
}    

您可以将问题分为一系列更简单的步骤:

  • 逐行读取输入
  • 收集“名称:值”对
  • 将对分组到记录中(每条记录以“构建”对开头)
  • 选择具有非空“BuildDate”、“Location”值的“Approved”记录
  • 使用给定的日期/时间格式查找最新记录
  • 实施:

    #!/usr/bin/env python
    import sys
    from datetime  import datetime
    from itertools import groupby
    
    # find all 'name: value' pairs
    file = sys.stdin
    pairs = ([s.strip() for s in line.partition(':')[::2]]
             for line in file if ':' in line)
    
    # group records
    def record_start(pair, count=[False]):
        """Mark start of a record."""
        if pair[0] == 'Build':
            count[0] = not count[0]
        return count[0]
    records = (dict(record) for _, record in groupby(pairs, record_start))
    
    approved = (r for r in records if r.get('Status') == 'Approved' and
                all(r.get(name) for name in "BuildDate Location".split()))
    
    # find latest record
    def get_date(record):
        try:
            return datetime.strptime(record['BuildDate'], '%m/%d/%Y %H:%M:%S')
        except ValueError:
            return datetime.min # handle invalid date strings
    
    latest = max(approved, key=get_date)
    assert get_date(latest) != datetime.min
    print(latest['Location'])
    
    请尝试以下代码:

    lastLocation = None
    lastTime = None
    skip = False
    
    bestLocation = None
    bestTime = None
    
    for line in text.split('\n'):    
        line.find('Location')
        if line.find('Location') == 0:
            # Build Location
            skip = False
            print "  Found Build location"
            lastLocation = line.split(":")[1].lstrip()       
        elif line.find('Status') == 0:
            # Status
            print "  Found Status"
            status = line.split(":")
            status1 = status[1].strip()
            if status1 != "Approved":
                skip = True
        elif line.find('BuildDate') == 0 and not skip:
            # Main Make
            print "  Found BuildDate"
            timeStr = line.split(":", 1)[1].lstrip()
            lastTime = datetime.datetime.strptime(timeStr, "%m/%d/%Y %H:%M:%S")
            if bestTime == None or bestTime < lastTime:
                bestTime = lastTime
                bestLocation = lastLocation
    print lastLocation
    
    lastLocation=None
    lastTime=无
    跳过=错误
    最佳位置=无
    最佳时间=无
    对于text.split('\n')中的行:
    line.find('位置')
    如果line.find('Location')==0:
    #构建位置
    跳过=错误
    打印“找到的生成位置”
    lastLocation=line.split(“:”[1]。lstrip()
    elif line.find('Status')==0:
    #地位
    打印“找到状态”
    状态=行。拆分(“:”)
    status1=状态[1]。条带()
    如果状态为1!=“批准”:
    跳过=真
    elif line.find('BuildDate')==0且不跳过:
    #主要品牌
    打印“找到构建日期”
    timeStr=line.split(“:”,1)[1].lstrip()
    lastTime=datetime.datetime.StrTime(timeStr,“%m/%d/%Y%H:%m:%S”)
    如果bestTime==无或bestTime
    由于出现以下错误,我怀疑格式是否正确。。lastTime=datetime.datetime.strptime(timeStr,“%m/%d/%Y%H:%m:%S”)文件“C:\python2.7.3\lib_strptime.py”,第328行,在_strpTimedata_string[found.end():])值错误:未转换的数据仍然存在:@user1795998如果您觉得我的答案有用,请投票支持我的答案并将其标记为接受。
    \\freeze\builds427\INTEGRATION\M1234BAAAANAA9321.3
    
    lastLocation = None
    lastTime = None
    skip = False
    
    bestLocation = None
    bestTime = None
    
    for line in text.split('\n'):    
        line.find('Location')
        if line.find('Location') == 0:
            # Build Location
            skip = False
            print "  Found Build location"
            lastLocation = line.split(":")[1].lstrip()       
        elif line.find('Status') == 0:
            # Status
            print "  Found Status"
            status = line.split(":")
            status1 = status[1].strip()
            if status1 != "Approved":
                skip = True
        elif line.find('BuildDate') == 0 and not skip:
            # Main Make
            print "  Found BuildDate"
            timeStr = line.split(":", 1)[1].lstrip()
            lastTime = datetime.datetime.strptime(timeStr, "%m/%d/%Y %H:%M:%S")
            if bestTime == None or bestTime < lastTime:
                bestTime = lastTime
                bestLocation = lastLocation
    print lastLocation