2017-04-06 20 views

回答

0

您可以使用此:

input = '''UB25X 
0060 4/22/16 -20.19 
0060 3/17/15 -23.37 
*UB25X 
FJ39Y 
0060 1/15/16 -27.34 
0060 7/15/16 -23.10 
*FJ39Y''' 

l = input.split('\n') 
tag = None 
out = [] 

for item in l: 
    if tag == item.replace('*',''): 
     tag = None 
    elif tag: 
     out.append(tag + ' ' + item) 
    else: 
     tag = item 

print out 
# ['UB25X 0060 4/22/16 -20.19', 'UB25X 0060 3/17/15 -23.37', 'FJ39Y 0060 1/15/16 -27.34', 'FJ39Y 0060 7/15/16 -23.10'] 
0

試試這個,以txt文件作爲第一個參數:

#!/usr/bin/python3 
# -*- coding: utf-8 -*- 

import sys 

file = sys.argv[1] 
f = open(file, 'r') 
prefix = None 

for line in f: 
    # continue if line is empty 
    if not line.strip(): 
     continue 
    # set prefix if it is not set and continue 
    if prefix is None: 
     prefix = line.strip() 
     continue 
    # unset prefix on given condition and continue 
    if line.startswith('*' + prefix): 
     prefix = None 
     continue 
    # if prefix is set and above does not apply print prefix plus line 
    if prefix is not None: 
     print(prefix + ' ' + line.strip()) 

f.close() 
+0

,幾乎都有,但前綴後的第一個沒有改變。第4行的前綴應改爲FJ39Y – Shawn

+0

UB25X變速箱0060 4/22/16 -20.19 – Shawn

+0

確實將第一行添加到所有以下行的前面,但添加的行應在產品更改時更改。第一行是庫存項目[NAME]的名稱,以下行是庫存交易,直到具有[* NAME]的記錄爲止。 – Shawn

相關問題