Home > Net >  Try statement in nested for-loop to bypass errors (syntax error )
Try statement in nested for-loop to bypass errors (syntax error )

Time:02-01

I have a data frame with the text entries dataframe['text'] as well as a list of features to compute for the function. Although not all features work for all text entries, so I was trying to compute everything possible, without manually checking which one worked for which entry. So I wanted the loop to continue after the point where it errors:

with Processor('config.yaml', 'en') as doc_proc:
    try:
        for j in range (0,len(features)): 
            for i in range (0, len(dataframe['text'])) :
                doc = doc_proc.analyze(dataframe['text'][i], 'string')
                result = (doc.compute_features([features[j]]))
                dataframe.loc[dataframe.index[i], [features[j]]]  = list(result.values())
             except: 
            continue

but I got the SyntaxError: unexpected EOF while parsing. The loop without try works, so I understand it's the reason but can't seem to find the correct way to change the syntax

CodePudding user response:

Put the try/except inside the loop. Then it will resume with the next iteration.

with Processor('config.yaml', 'en') as doc_proc:
    for feature in features: 
        for i in range (0, len(dataframe['text'])):
            try:
                doc = doc_proc.analyze(dataframe['text'][i], 'string')
                result = (doc.compute_features([feature]))
                dataframe.loc[dataframe.index[i], [feature]]  = list(result.values())
            except:
                pass
  •  Tags:  
  • Related