我总是遇到零除错误

0 投票
3 回答
592 浏览
提问于 2025-04-18 13:41

写一个程序,先让用户输入一个文件名,然后打开这个文件,逐行读取内容,寻找像这样的行:
X-DSPAM-Confidence: 0.8475
统计这些行的数量,并从每一行中提取出小数值,计算这些值的平均数,并输出结果。

这是我的Python代码:

# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
inp = fh.read()
count = 0
total = 0
for line in inp:
    if not line.strip().startswith("X-DSPAM-Confidence:") : continue
    pos = line.find(':')
    num = float(line[pos+1:]) 
    total = float(total + num)
    count = float(count + 1)
print 'Average spam confidence:', float(total/count)

我其实不太明白发生了什么,因为我在第13行(代码的最后一行)总是遇到零除错误。

3 个回答

0

我觉得它没有正确读取文件,所以就不会进入这个循环。

fh = open(fname)
inp = fh.read()

试试这个,看看它是否进入了循环。

fname = raw_input("Enter file name: ")
fh = open(fname)
inp = fh.read()
count = 0
total = 0
for line in inp:
  print inp 
1

你的 if 语句跳过了 for 循环的其他部分,因为 line.strip.startwith("X-DSPAM-Confidence:") 这个条件总是返回假,也就是说它从来没有满足过。

所以,count 这个变量的值一直没有增加,始终保持在 0,这就导致了你在进行除法运算时出现了除以零的错误。

1

当找不到字符串 X-DSPAM-Confidence: 时会发生什么?

如果你的代码找不到这个字符串,那么 Count 变量的值就会一直是零,这样就可能会出现除以零的错误。

在最后计算之前,试着先检查一下 Count 的值...

也许可以这样做:

If Count>0 print 'Average spam confidence:', float(total/count)

(这可能不是正确的 Python 语法,因为我从来没有用过 Python)

撰写回答