Reputation: 29
I'm trying to write data to a txt file in a for loop using the code [python]:
f = open('top_5_predicted_class.txt', 'w')
f.write('Predicted Classes' + '\t\t' + ' Class Index' + '\t' + ' Probability' + '\n\n')
for i in range(0, 5):
f.write("%s \t \t %s \t \t %s \n" % (labels[top_k][i], top_k[i], out['prob'][0][top_k][i]) )
f.close()
But the output that I got was not what I was expecting. I want to have class index all left aligned as well as the probabilities.
Any idea of how can I do this? I guess the problem exists because the length of the predicted classes is not fixed.
Upvotes: 1
Views: 7335
Reputation:
You can go through your data and get the maximum field widths and then use them to align everything:
data = [
['tabby, tabby cat', 281, 0.312437],
['tiger cat', 282, 0.237971],
['Egyption cat', 285, 0.123873],
['red fox, Vulpes vulpes', 277, 0.100757],
['lynx, catamount', 287, 0.709574]
]
max_class_width = len('Predicted Classes')
max_index_width = len('Class Index')
max_proba_width = len('Probability')
for entry in data:
max_class_width = max(max_class_width, len(entry[0]))
max_index_width = max(max_index_width, len(str(entry[1])))
max_proba_width = max(max_proba_width, len(str(entry[2])))
print "{1:<{0}s} {3:<{2}s} {5:<{4}}".format(max_class_width, 'Predicted Classes',
max_index_width, 'Class Index',
max_proba_width, 'Probability')
for entry in data:
print "{1:<{0}s} {3:<{2}s} {5:<{4}}".format(max_class_width, entry[0],
max_index_width, str(entry[1]),
max_proba_width, str(entry[2]))
Output
Predicted Classes Class Index Probability
tabby, tabby cat 281 0.312437
tiger cat 282 0.237971
Egyption cat 285 0.123873
red fox, Vulpes vulpes 277 0.100757
lynx, catamount 287 0.709574
You can use also use printf
style formatting:
print "%-*s %-*s %-*s" % (max_class_width, 'Predicted Classes',
max_index_width, 'Class Index',
max_proba_width, 'Probability')
for entry in data:
print "%-*s %-*s %-*s" % (max_class_width, entry[0],
max_index_width, str(entry[1]),
max_proba_width, str(entry[2]))
Upvotes: 1
Reputation: 8254
You shouldn't use tabs for this kind of alignment, since the behavior is unpredictable when your inputs are of different length. If you know what the maximum length of each column is, you can use the format
function to pad with spaces. In my example, I use 15 spaces:
>>> for a,b,c in [('a','b','c'), ('d','e','f')]:
... print ("{: <15} {: <15} {: <15}".format(a, b, c))
...
a b c
d e f
This is purely about display though. If you are concerned about storing the data, it would be much better to use CSV format, such as with Python's csv
module.
Upvotes: 2