1

我正在尝试使用代码 [python] 在 for 循环中将数据写入 txt 文件:

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()

但是我得到的输出不是我所期望的。我想让类索引和概率都左对齐。

输出

知道我该怎么做吗?我想问题存在是因为预测类的长度不固定。

4

2 回答 2

2

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.

于 2016-10-27T13:24:38.487 回答
1

您可以浏览数据并获取最大字段宽度,然后使用它们来对齐所有内容:

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]))

输出

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   

您还可以使用printf样式格式:

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]))
于 2016-10-27T14:20:27.543 回答