简体   繁体   中英

How to skip error and continue to run for loop and continue to the next line

    
    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

I am trying to do here is to create a function to read a column from an excel sheet and remove special characters and punctuation, after that save it into a new excel sheet.

The column consists of a string that has multiple sentences and special characters. I manage to remove those special characters and punctuation, however, there is a single line in the column that is completely empty.

When the code reaches that line(line 506) it gives out an error that there needs to be a string or byte inside. I used try and except so the error does not show up but the code just ends there. How do I make it skip (line507) that line and continue(line508) running the function? Thanks in advance!

You can do this:

   
    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)
    

Your try and except is in the wrong place.

When you get an error in the try block

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

The execution of this whole block is stopped and the except block is called.

    except:
        pass

This is at the end of the function so the function ends and returns None

To fix that put the try block around cleanstr = re.sub(r'[^\\w\\s]', ' ', words) and instead of pass ing use continue so the control goes back to the next word in the loop.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM