【发布时间】:2014-09-17 01:56:26
【问题描述】:
我有一个包含大约 50 个 .txt 文件的文件夹,其中包含以下格式的数据。
=== Predictions on test data ===
inst# actual predicted error distribution (OFTd1_OF_Latency)
1 1:S 2:R + 0.125,*0.875 (73.84)
我需要编写一个程序,结合以下内容:我的索引号 (i)、真实类的字母(R 或 S)、预测类的字母、以及每个分布预测(小数点后大于 1.0)。
我希望它在完成后如下所示,但最好是 .csv 文件。
ID True Pred S R
1 S R 0.125 0.875
2 R R 0.105 0.895
3 S S 0.945 0.055
. . . . .
. . . . .
. . . . .
n S S 0.900 0.100
我是一个初学者,对于如何将所有这些解析然后连接和附加有点模糊。这就是我的想法,但如果这样更容易,请随意提出另一个方向。
for i in range(1, n):
s = str(i)
readin = open('mydata/output/output'+s+'out','r')
#The files are all named the same but with different numbers associated
output = open("mydata/summary.csv", "a")
storage = []
for line in readin:
#data extraction/concatenation here
if line.startswith('1'):
id = i
true = # split at the ':' and take the letter after it
pred = # split at the second ':' and take the letter after it
#some have error '+'s and some don't so I'm not exactly sure what to do to get the distributions
ds = # split at the ',' and take the string of 5 digits before it
if pred == 'R':
dr = #skip the character after the comma but take the have characters after
else:
#take the five characters after the comma
lineholder = id+' , '+true+' , '+pred+' , '+ds+' , '+dr
else: continue
output.write(lineholder)
我认为使用索引将是另一种选择,但如果任何文件中的间距关闭并且我还没有确定这一点,它可能会使事情复杂化。
感谢您的帮助!
【问题讨论】:
标签: python python-2.7 csv export-to-csv