0

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

输出如下:

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' % (cell),这样它就不会显示结尾的零了吗?

谢谢!

4

2 回答 2

3

请参阅Python 字符串格式化文档。“%6f”是你的问题。相反,尝试

print "%.2f" % cell
于 2013-01-27T19:25:01.767 回答
1

数字 = 12.3456

new_val = '%.2f' % float(num)

打印浮点数(new_val)

12.34

于 2015-09-30T07:36:02.880 回答