我正在尝试生成Python代码以获取遵循特定格式的文本文件中的输出。我想要的格式是:如果在随后的几行中,条目的顺序在某一点相同,则删除到该点的所有条目(保留最后一个)并生成最终的文本文件。在以下各节中,我将描述我要做什么和得到什么。 Data File Python Code
outputfile = open('webgrapviz.txt', 'w')
for data in all_data:
line=""
for k,item in enumerate(data):
if len(item)==0: continue
if len(line)==0:
line=line+'"'+item+'"'
else:
line=line+"-> "+'"'+item+'"'
line = line + "\n"
outputfile.write(line)
outputfile.close()
我得到的输出是:
"Subsea Production"-> "Subsea Landing String Services"-> "SenTURIAN E&A Well Test Subsea Landing String Electrohydraulic Operating System"
"Subsea Production"-> "Subsea Landing String Services"-> "SenTURIAN Large-Bore Subsea Landing String Electrohydraulic Operating System"
"Subsea Production"-> "InterventionConstrained & Subsea Applications"-> "MaxFORTE High-Reliability ESP System"
"Subsea Production"-> "Intervention-Constrained & Subsea Applications"-> "ZEiTECS Shuttle Rigless ESPReplacement System"
"Subsea Production"-> "OneSubsea, a Schlumberger company"
我想要的输出是:
"Subsea Production"-> "Subsea Landing String Services"-> "SenTURIAN E&A Well Test Subsea Landing String Electrohydraulic Operating System"
"Subsea Landing String Services"-> "SenTURIAN Large-Bore Subsea Landing String Electrohydraulic Operating System"
"Subsea Production"-> "InterventionConstrained & Subsea Applications"-> "MaxFORTE High-Reliability ESP System"
"Intervention-Constrained & Subsea Applications"-> "ZEiTECS Shuttle Rigless ESPReplacement System"
"Subsea Production"-> "OneSubsea, a Schlumberger company"
答案 0 :(得分:0)
首先想到的是,也许在性能方面有更好的方法。
outputfile = open('webgrapviz.txt', 'w')
prev_data = []
for data in all_data:
data = [x for x in data if x] # Filter empty strings
if not data:
continue
# Compare with previous data and get the index where they differ
index = 1
if prev_data:
for index, (first, second) in enumerate(zip(data, prev_data)):
if first != second:
break
prev_data = data
data = data[index-1:] # Remove repeated items
data = map(lambda x: '"%s"' % x, data) # Add double quotes
line = "-> ".join(data) + "\n" # Generate line with join
outputfile.write(line)
outputfile.close()
输出文件:
"Subsea Production"-> "Subsea Landing String Services"-> "SenTURIAN E&A Well Test Subsea Landing String Electrohydraulic Operating System"
"Subsea Landing String Services"-> "SenTURIAN Large-Bore Subsea Landing String Electrohydraulic Operating System"
"Subsea Production"-> "Intervention-Constrained & Subsea Applications"-> "MaxFORTE High-Reliability ESP System"
"Intervention-Constrained & Subsea Applications"-> "ZEiTECS Shuttle Rigless ESPReplacement System"
"Subsea Production"-> "OneSubsea, a Schlumberger company"