有关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
- 有关Python中的division问题
- python中的python from __future__ import division
- Python Division //
- Python自然语言处理小问题之from __future__ import division
- 有关于python中的换行
- Python Division and Remainders
- 有关java中的引用问题
- 有关SQL中的计算问题
- 有关 Python 中的 File.readlines(sizehint) 函数
- 有关python中的pylab的下载安装
- 有关python中的id,is 等
- 有关ms100题中的python实现
- python from __future__ import division
- 【Hacker Rank】05.Python: Division
- python from __future__ import division
- python from __future__ import division
- Python from __future__ import division
- python中有关赋值的问题
- vs调试debug超级慢的一个解决方法
- Firefox浏览器打不开网页
- 19. Remove Nth Node From End of List
- MFC中拖动无标题的对话框
- rk3188--2.linux-3.0.36中内核参数的读取与传递
- 有关Python中的division问题
- java并发编程(二十四)--面试题合集
- 处理问题的思路,基于SSM项目(spring,springmvc,mybatis)
- 微信支付之公众号支付
- HTML + css 页面按比例排版
- OpenCV学习Object Segmentation
- rk3188--3.initramfs_data.cpio的生成及使用
- 番茄工作法笔记
- iOS毛玻璃效果实现