数据挖掘分配

时间:2017-05-02 22:40:25

标签: python

我被要求完成这项任务,我遇到很大困难,有人可以帮忙吗? “编写一个Python程序,要求用户输入库存数据文件名(.csv格式)[类似于'课程材料'下给出的'stockdata.csv'文件',请求列号,然后读取该文件总计指定列中的值。然后程序应该打印指定列的平均值。“

#initialize variables
column = 0
fh = 0

#function1
def openfile():
    while True:
        fname = raw_input ("Enter File Name: ")
        try:
            fhand = open(fname)
        except:
            print "File not found. Enter valid file name."
            continue
        break
    return fhand

#function2
def processfile (f,c):
    tot = 0.0
    count = 0
    for line in f:
        anyline = line.split(',')
        if line.startswith('Date'):
            continue
        tot = tot + float(anyline[c])
        count = count + 1
    avg = tot/count
    print "Column Average: ", avg

#main
fh = openfile()
while True:
    column = raw_input('Enter column number: ')
    try:
        column = int(column)
    except:
        print "Please Enter A Valid Input"
        continue
    break
processfile(fh, column)

但这给了我错误

Traceback (most recent call last): File "/home/ubuntu/workspace/ex50/tests/stockdatafile.py", line 40, in <module> processfile(fh, column)     
File "/home/ubuntu/workspace/ex50/tests/stockdatafile.py", line 27, in processfile avg = tot/count ZeroDivisionError: float division by zero

,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

当涉及到processfile函数时,for循环不会完全运行。这反过来意味着您的counttot变量保持在00.0

avg = tot/count运行时,当您尝试将tot的{​​{1}}除以0.0

时,您会收到错误