2

目標:-ステータスが承認され、ビルド日付が最新の場合、以下の入力でファイルを解析し、最新の(ビルド日付のタイムスタンプが最新である必要があります)場所を取得する必要があります..サンプルの入力と出力を提供しました。コードは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 );
    }                                                           
}    

印刷"$location \ n"; '\ freeze \ builds427 \ INTEGRATION \ M1234BAAAANAAW9321.3

私はPythonで次のように書き込もうとしましたが、うまくいかないようです。目標を達成するためのより良い実装があるかどうか疑問に思っています。提案してください

for line_info in lines:

    line_info.find('Location')

    if line_info.find('Location') == 0:
        # Build Location
        print "  Found Build location"
        logString += "  Found Build location\n"
        location = line_info.split(" ")
        location1 = location[len(location)-1]
    elif line_info.find('Status') == 0:
        # Status
        print "  Found Status"
        logString += "  Found Status\n"
        status = line_info.split(" ")
        removeEmpty(status)
        status1 = status[1].strip()
        if status1 != "Approved"
        goto .start
    elif line_info.find('BuildDate') == 0:
        # Main Make
        print "  Found BuildDate"
        logString += "  Found BuildDate\n"
        builddate1 = line_info.split(" ")
        removeEmpty(builddate1)
        builddate1 = builddate1[1]
        #if builddate1 > 
4

2 に答える 2

0

問題を一連のより単純なステップに分割することができます。

  1. 入力を1行ずつ読み取る
  2. '名前:値'のペアを収集します
  3. ペアをレコードにグループ化します(各レコードは「ビルド」ペアで始まります)
  4. 空白以外の「BuildDate」、「Location」の値を持つ「Approved」レコードを選択します
  5. 指定された日付/時刻形式を使用して最新のレコードを検索します

実装:

#!/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'])

出力

\\freeze\builds427\INTEGRATION\M1234BAAAANAA9321.3
于 2012-11-03T07:47:00.683 に答える
0

このコードを試してください:

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
于 2012-11-03T07:48:54.850 に答える