我有一个大文件(下面的示例),其中包含我尝试使用python重新格式化的数据(下面的代码)。
文件:
Segment 30
XXXXXXXXXXXXXXXXXXXXXXXX
Sequuo: ju0
saeer on werarms23e: 610
//
Segment 30
XXXXXXXXXXXXXXXXXXXXXXXX
Sequuo: xu0
saeer on werarms23e: 400
//
我想要一个制表符分隔的格式化输出,如下所示。
预期产出:
Sequuo saeer on werarms23e
ju0 610
xu0 s400
到目前为止我的尝试:
row=[]
with open("file.txt","r") as infile:
while True:
for line in infile:
if line.startswith("Sequuo:"):
line1=line.replace("\t","")
line1=line.split(":")
row.append(line1[1].strip())
#line1=line.replace("\n","\t")
if line.startswith("saeer on werarms23e:"):
line1=line.replace("\t","")
line1=line.split(":")
row.append(line1[1].strip())
print row
if line.startswith("//"):
break
if line=="":
break
有谁知道如何正确使用此代码?
由于
答案 0 :(得分:1)
如果预期的o / p是
Sequuo saeer on werarms23e
ju0 610
xu0 400
然后试试这段代码:
import sys
row=[]
with open("file.txt","r") as infile:
while True:
for line in infile:
if line.startswith("Sequuo:"):
line1=line.replace("\t","")
line1=line.split(":")
row.append(line1[1].strip())
#line1=line.replace("\n","\t")
if line.startswith("saeer on werarms23e:"):
line1=line.replace("\t","")
line1=line.split(":")
row.append(line1[1].strip())
if line.startswith("//"):
break
if line=="\n":
break
print ('Sequuo saeer on werarms23e')
count = 0
for i in row:
count +=1
sys.stdout.write (i + '\t')
if not count%2:
print