有关Python中的division问题

来源:互联网 发布:java redis 订阅发布 编辑:程序博客网 时间:2024/06/16 16:22

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

import nltkdef 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())),也就不再报错了。

0 0
原创粉丝点击