2015-02-05 166 views
0

我的程序是查找類型數量,令牌數量和類型與令牌比率。但是,我不知道如何告訴Python ttr的答案不是整數。如何知道python我需要小數?

from nltk.corpus import inaugural 

print inaugural.fileids() 

tokens = inaugural.words("1789-Washington.txt") 

numtokens = len(tokens) 
print numtokens 

types = sorted(set(tokens)) 
numtypes = len(types) 
print numtypes 

# This is the part I'm unsure about.  
ttr = numtypes/numtokens 
print ttr 

回答

2

如果您在Python 3個工作,除法運算符/默認情況下,執行浮點除法:

>>> 3/2 
1.5 
>>> 4/2 
2.0 

因爲整數除法是由//操作處理。

在Python 2.x中,如果你想在整數除法精確到小數點,您可以提名者或分母轉換爲float(),像這樣:

ttf = float(numtypes)/numtokens 

此外,作爲tobias_k指出,你可以不要

>>> from __future__ import division 
>>> 3/2 
1.5 

得到Python3式的分工在Python 2.x的

+1

或'從__future__進口division' – 2015-02-05 22:24:37

+1

浮法()方法奏效FO r my python 2.感謝您的及時回覆! – Auborey 2015-02-05 22:28:03