如何跳过错误并继续运行for循环并继续下一行

2024-10-03 21:31:05 发布

您现在位置:Python中文网/ 问答频道 /正文

counti=0

def removepunc(firstlist):
    global counti
    try:
        for words in firstlist:
            cleanstr = re.sub(r'[^\w\s]', ' ', words)
            counti += 1
            print(counti,":", cleanstr)
            Appended_Data.to_excel("test.xlsx", index=False)
        return(counti,":", cleanstr)
    except:
        pass

我在这里试图做的是创建一个函数,从excel工作表中读取一列并删除特殊字符和标点符号,然后将其保存到新的excel工作表中

该列由具有多个句子和特殊字符的字符串组成。我设法删除了那些特殊字符和标点符号,但是,列中有一行是完全空的

当代码到达该行(第506行)时,它会发出一个错误,即代码中需要有一个字符串或字节。我使用了try和except,因此不会显示错误,但代码就到此结束。如何使其跳过(第507行)该行并继续(第508行)运行该函数


Tags: 函数字符串代码def错误excelwordstry
2条回答

你的tryexcept放错地方了

try块中出现错误时

    for words in firstlist:
        cleanstr = re.sub(r'[^\w\s]', ' ', words)
        counti += 1
        print(counti,":", cleanstr)
        Appended_Data.to_excel("test.xlsx", index=False

停止执行整个,并调用except

    except:
        pass

这是函数的结尾,因此函数结束并返回None

要修复此问题,请将try块放在cleanstr = re.sub(r'[^\w\s]', ' ', words)周围,并使用pass代替continue,以便控件返回循环中的下一个单词

def removepunc(firstlist):
    global counti
    for words in firstlist:
        try:
            cleanstr = re.sub(r'[^\w\s]', ' ', words)
        except:
            # Not sure if you want to increase counti here
            # if so add the line here
            continue 
        counti += 1
        print(counti,":", cleanstr)
        Appended_Data.to_excel("test.xlsx", index=False)
    return(counti,":", cleanstr)

您可以这样做:

   
    def removepunc(firstlist):
        global counti
        for words in firstlist:
            try:
               cleanstr = re.sub(r'[^\w\s]', ' ', words)
            except:
               continue
            counti += 1
            print(counti,":", cleanstr)
            Appended_Data.to_excel("test.xlsx", index=False)
        return(counti,":", cleanstr)
    

相关问题 更多 >