我在文本文件中有这种形式的数据。
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
我想打印此输出:
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 :(得分: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']
答案 1 :(得分: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()