处理错误,尝试并除外

时间:2020-05-03 16:09:50

标签: python-3.x error-handling

我的函数收到一个CSV文件,需要先检查它,然后才能进行实际任务(计算平均值)。如果“ if”条件为true,则尝试引发异常,但最后在“打印”行中出现SyntaxError。我尝试了其余的代码,并且工作正常。我只是尝试处理CSV文件的测试(这只是其中的一个,我需要稍后再插入一些),然后再开始第二个“ for循环”,但我没有得到语法错误。 谢谢!

def calc_profit_per_group(in_file):

lines= f.readlines()
series_names=[]
dicta={'happy':0, 'sad':0, 'neutral':0}
counter_happy= 0
happy_movies= 0
counter_sad= 0
sad_movies= 0
counter_neutral= 0
neutral_movies= 0
count=0

try:

    for line in lines:
        tokens= line.rstrip().split(',')
        series_names.append(tokens[0])
    for i in range(len(series_names)):
        if series_names[i] in series_names[i+1:]:
            raise exception


    for line in lines:
        line_list= line.rstrip().split(',')
        if line_list[2]== "happy":
            happy_movies= happy_movies+float(line_list[1])
            counter_happy+=1
        elif line_list[2]== "sad":
            sad_movies= sad_movies+float(line_list[1])
            counter_sad+=1
        elif line_list[2]== "neutral":
            neutral_movies= neutral_movies+float(line_list[1])
            counter_neutral+=1
    dicta['happy']= happy_movies/counter_happy
    dicta['sad']= sad_movies/counter_sad
    dicta['neutral']= neutral_movies/counter_neutral

    return dicta

except exception:
    print("The series " + str(series_names[i]) + " appears more than once") from None
    return {}

0 个答案:

没有答案