浮点 - python:在制表浮点数时仅显示两个十进制数字



我写了一个代码来解析一些文本文档,并显示一些单词出现的频率。

输出如下:

Counting words by tag
---------------------
modals
per 1000 words                    can  could  shall should   will  would
austen-emma.txt                1.480000 4.350000 1.100000 1.920000 2.900000 4.260000
austen-persuasion.txt          1.090000 4.590000 0.560000 1.920000 1.650000 3.620000
austen-sense.txt               1.500000 4.060000 0.870000 1.640000 2.500000 3.600000
chesterton-ball.txt            1.460000 1.210000 0.510000 0.770000 2.040000 1.440000
chesterton-brown.txt           1.500000 1.990000 0.350000 0.650000 1.290000 1.570000
chesterton-thursday.txt        1.760000 2.180000 0.710000 0.780000 1.570000 1.730000

如您所见,数字四舍五入到百分之一,但我的程序仍然打印一些过多的零。

这在制表上,即在以下代码行上

     cell = round(float(cfdist[fileid][w])*1000/number_of_words[fileid],2)
     print '%6f' % (cell),  

有人能帮我改进行打印"%6f"%(单元格),这样它就不会显示结尾零吗?

谢谢!

请参阅 Python 字符串格式设置文档。"%6f"是您的问题。相反,请尝试

print "%.2f" % cell

num = 12.3456

new_val = '%.2f' % 浮点数(数字)

打印浮点(new_val)

12:34

最新更新