【问题标题】:how to get try/except works without error如何让 try/except 正常工作
【发布时间】:2020-10-22 13:57:49
【问题描述】:

我正在尝试解析大量文件以在一张表中获取一些信息。这是我的脚本:

import pandas as pd
import numpy as np
M1 = pd.DataFrame(Test,columns=['Test'])

for sample in samples:
    with open("file/"+sample+".txt") as f:
        c=0
        tpm=[]
        for line in f:
            c+=1
#                if c==1:
#                    if line.split('/')[1].split('.')[0]!='abc':
#                        break
            if c>2 and line.startswith('gene'):
                try:
                    return tpm.append(int(line.rstrip().split('\t')[6])/int(line.rstrip().split('\t')[5])*1000)
                except ZeroDivisionError:
                    return 0

M1[Test]=tpm/np.sum(tpm)*1000000
M=M1
M=M.fillna(0)
M.index=M['Test']
M.to_csv('M.xls',index=False,sep='\t')'

如果没有包含 try:except ZeroDivisionError 的行,它可以工作,但我收到 ZeroDivision 错误,结果无法用于下一行。所以我想在 *.txt 文件中遇到 0 时加 0 而不是除法。

在这个脚本中我遇到了'return' outside function 语法错误

我尝试了很多方法,例如在for line in f: 之前添加try 或添加except: pass,但没有奏效。

【问题讨论】:

  • SyntaxError: 'return' outside function 你不能捕捉到SyntaxError,你不应该在函数之外有return 语句
  • 你无法捕捉到 this SyntaxError,因为它是由解析器引发的,而不是在运行时(为了适当区分解析/编译时间和运行时)。 (例如,execeval 可以在运行时引发 SyntaxErrors,这些都可以被捕获。)
  • 那条消息有什么不清楚的地方?您没有任何功能,与 try-except 无关。即使你这样做了,那里的返回也会在第一次出现后停止你的循环,所以这不是你想要的,我猜

标签: python


【解决方案1】:

正如我所评论的,您无法捕获 SyntaxError,因此您不应在函数外部使用 return 语句。如果您的意图是在出现 ZeroDivisionError 时添加 0,您可以在 except 部分中更改您的代码。这样,如果遇到ZeroDivisionError,您将添加0

try:
    tpm.append(int(line.rstrip().split('\t')[6])/int(line.rstrip().split('\t')[5])*1000)
except ZeroDivisionError:
    tpm.append(0)

编辑:@chepner 指出一些SyntaxErrors 仍然可以被more info in this SO answer 捕获。

【讨论】:

    【解决方案2】:

    这里真正的问题是你在函数之外使用了返回命令, return 只能在函数定义中使用

    但是你的逻辑实现是正确的:Try/except 的使用是正确的

    但是,将值存储在变量中并检查第二个值是否等于零是很方便的,在这里您可以删除 try/except 块。

     try:
         a=tpm.append(int(line.rstrip().split('\t')[6])
         b=int(line.rstrip().split('\t')[5])*1000)
         if b==0:
            print(a/b)
         else:
            print(0)
    except ZeroDivisionError:
         print(0)
    

    但是在值不等于零的情况下计算您的数量,但它太小了: 比如 1/(10**9999999999999999999999999999999999999999999999999),这里的值不等于 0,但是需要时间来评估, 所以创造这样的条件是黄油:

    if round(x,10)==0:
    

    【讨论】:

      【解决方案3】:

      您在函数定义之外使用return 语句。

      你可以避免return all-together 并使用赋值或其他一些逻辑,或者用def 块包装整个事情并调用它。

      但后者在您的情况下没有意义(b/c return 将打破 for 循环)。所以重新安排你的代码如下。

      [...]  
             
           try:
                tpm.append(int(line.rstrip().split('\t')[6])/int(line.rstrip().split('\t')[5])*1000)
           except ZeroDivisionError:
                pass
      

      【讨论】:

        猜你喜欢
        • 2014-05-04
        • 2017-05-20
        • 2015-05-08
        • 2020-08-27
        • 2018-06-11
        • 2016-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多