有关Python中的division问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012505432/article/details/51658519

笔者在学习Natural Language Processing with PythonChapter2的过程中,在运行如下代码的时候生成结果和书中示例不同:

import nltk

def content_fraction(text):
    stopwords = nltk.corpus.stopwords.words('english')
    content = [w for w in text if w.lower() not in stopwords]
    return len(content)/len(text)

print content_fraction(nltk.corpus.reuters.words())

返回结果本应为0.735240435097661,实际返回0。说明是在除法运算的过程中,因为被除数为int型,所以结果发生了截断,可将return len(content)/len(text)语句改为return len(content)/float(len(text)),运行结果正确。
同时在查看stackoverflow的时候,有人给出了建议,在代码最前面添加from __future__ import division即可,后面就不需要特别注释float型。
同时我也产生了一个疑问,为什么要用future呢,stackoverflow中也有人给了详细的解释:

You’re using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.

笔者用的正是Python2.7,于是换成Python3.4,直接运行原代码仍然报错。原来Python3.4对于print语句进行了格式上的修改。将最后一句修改为print (content_fraction(nltk.corpus.reuters.words())),也就不再报错了。

猜你喜欢

转载自blog.csdn.net/u012505432/article/details/51658519