如何将文本文件中的第一行添加到后续行,直到满足条件,然后重复?

2024-05-17 11:13:48 发布

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

我在一个文本文件中有这种形式的数据

UB25X型

0060 2016年4月22日-20.19

0060 2015年3月17日-23.37

*UB25X

FJ39Y型

0060 2016年1月15日-27.34

0060 2016年7月15日-23.10

*FJ39Y型


我要打印此输出:

UB25X 0060 4/22/16-20.19

UB25X 0060 2015年3月17日-23.37

FJ39Y 0060 2016年1月15日-27.34

FJ39Y 0060 2016年7月15日-23.10


Tags: 数据形式文本文件ub25xfj39y
2条回答

尝试以下操作,将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()

您可以使用:

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']

相关问题 更多 >