【问题标题】:properly using exceptions while interating through lines python在遍历行 python 时正确使用异常
【发布时间】:2015-01-19 01:33:21
【问题描述】:

尝试编写代码,在调用方法后代码将遍历行,直到找到其中只有一个数字的行。然后它将将该数字添加到一个金额中。这就是我正在考虑的问题,我无法完全解决这个问题。

 elif line == 'o' or line == 'O':
 amount = next(f)
            try:
                next(f)
            except TypeError:
                next(f)
            print(line)#DEBUG TEST****
            score.updateOne(amount)

所以尝试做的是,如果一行包含字母 o,那么它将转到下一行并将其添加到一个数量。但如果金额是空格或字符串。我需要它来尝试添加下一行。如果这不起作用,请尝试下一个,直到找到数字并将其添加到该行。

在线研究已经让我走到了这一步,但是请其他人填补空白吗?

谢谢

为了更好的理解,这里是代码试图读取的文件:

50

30

40

M

10 20 30

o

5

1 2 3

X

这是函数中使用类方法执行任务的代码。我没有发布课程及其方法,因为没有意义

score = Score() # initize connection       

def processScores(file, score):

使用 with 方法打开文件,用 for 循环读取每一行。如果内容在行

同意elif语句中的参数,执行if语句中的代码。否则,忽略行

with open(file,'r') as f:
    for line in f:  #starts for loop for all if statements
        line = line.strip()
        if line.isdigit():
            start = int(line)
            score.initialScore(start)
            print(line)#DEBUG TEST**** #checks if first line is a number if it is adds it to intial score

        elif len(line) == 0:
            print(line)#DEBUG TEST****
            continue        #if a line has nothing in it. skip it  

        elif line == 'o' or line == 'O':
            try:
                amount = int(line)
            except ValueError:
                continue
            else:
                score.updateOne(amount)
            amount =  next(f)
            print(line)#DEBUG TEST****
            score.updateOne(amount) #if line contains single score marker, Takes content in next line and
                                    #inserts it into updateOne

        elif line == 'm'or line == 'M':
            scoreList = next(f);next(f)
            lst = []
            for item in scoreList:
                print(line)#DEBUG TEST****
                lst.append(item)
                score.updateMany(lst) # if line contains list score marker, creates scoreList variable and places the next line into  that variable
                                      # creates lst variable and sets it to an empty list
                                      # goes through the next line with the for loop and appends each item in the next line to the empty list
                                      # then inserts newly populated lst into updateMany

        elif line == 'X':
            print(line)#DEBUG TEST****
            score.get(self)
            score.average(self) # if line contains terminator marker. prints total score and the average of the scores.
                                # because the file was opened with the 'with' method. the file closes after 
        
                
        
        




    
    

【问题讨论】:

    标签: python file exception exception-handling


    【解决方案1】:

    而不是写:

    try:
        next(f)
    except ValueError:
        next(f)
    

    您需要在try 块中进行类型转换。例如:

    for line in f:
        try:
            # try to convert the line to a number
            value = float(line)
        except ValueError:
            # oops! It wasn't a number... continue on with the next line.
            continue
        else:
            # good! It was a number, update the score.
            score.updateOne(value)
    

    您的原始代码使用了很多next 来推进迭代器,但这通常是不必要的麻烦。例如,如果您读取文件的末尾,并且您没有在代码中处理这些内容,您的 next 调用将抛出 StopIteration。更好的方法是利用f 可以迭代的事实(即假设f 是一个开放的、类似文件的对象),因此编写for line in f: 是您循环所需要做的所有事情在文件的行上。

    现在,您的文件有一个特殊的结构,其中oO 表示您要读取的传入值。这里有一些代码可以做到这一点:

    total = 0
    with open("data.txt") as f:
        for header in f:
            if header.strip().lower() == "o":
                for line in f:
                    try:
                        value = int(line)
                    except ValueError:
                        continue
                    else:
                        total += value
                        break
                else:
                    raise RuntimeError("No value found!")
    

    如果您的文件格式错误,这将抛出 RuntimeError,这意味着它有一个 o 后面没有值。

    【讨论】:

    • 谢谢。一个简单的问题,我必须使用浮点数吗?或者我可以改用 Int 吗?
    • @eatAllYourPiePeter 你当然可以使用int,如果这是你所期望的。
    • 我也不确定这是否有效。因为我仍然需要它来找到'o'之后的数字,所以像这样:o(代码认为哦,看起来'O'让我们找到一个数字)''(那是一个空白空间,我无能为力,我需要我的数字 5(老兄,它是一个数字。是的,我需要将其添加到金额中),然后当然按其他方法,谢谢您的帮助
    • @eatAllYourPiePeter 然后你可以在循环中使用状态机。将状态保存在变量中,并使用 if/elif 构造根据每个状态进行操作。
    • @eatAllYourPiePeter 啊,我错过了这个要求。我添加了一些代码来做到这一点,并避免使用next 调用。
    【解决方案2】:

    我希望你正在尝试读取文件,如果是,那么代码应该类似于

    score = 0
    with open('mydata.txt') as fp:
      for line in iter(fp.readline, ''):
         try:
             score += int(line)
         except ValueError as e:
             print "something is wrong with value "+e.message
    
    print score
    

    【讨论】:

    • with 块内的代码应该缩进。
    猜你喜欢
    • 2015-09-27
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 2016-06-25
    • 2018-02-03
    • 2017-12-12
    相关资源
    最近更新 更多