问题描述
编写一个程序,提示输入文件名,然后打开该文件并读取该文件,查找格式如下的行:
X-DSPAM-Confidence: 0.8475
对这些行进行计数,从每行中提取浮点值,然后计算这些值的平均值并产生如下所示的输出。请勿在解决方案中使用sum()
函数或名为sum
的变量。*
这是我的代码:
fname = input("Enter a file name:",)
fh = open(fname)
count = 0
# this variable is to add together all the 0.8745's in every line
num = 0
for ln in fh:
ln = ln.rstrip()
count += 1
if not ln.startswith("X-DSPAM-Confidence: ") : continue
for num in fh:
if ln.find(float(0.8475)) == -1:
num += float(0.8475)
if not ln.find(float(0.8475)) : break
# problem: values aren't adding together and gq variable ends up being zero
gq = int(num)
jp = int(count)
avr = (gq)/(jp)
print ("Average spam confidence:",float(avr))
问题是,当我运行代码时,它指出存在错误,因为num
的值为零。所以我收到了这个:
ZeroDivisionError: division by zero
当我将num
的初始值更改为None
时,会发生类似的问题:
int() argument must be a string or a number,not 'NoneType'
当我将其放在代码顶部时,python COURSERA自动分级机也不会接受它:
from __future__ import division
他们提供给我们的示例数据的文件名为“ mbox-short.txt”。这是链接http://www.py4e.com/code3/mbox-short.txt
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)