Home > Mobile >  Looking for a cleaner code to map a list of dict result
Looking for a cleaner code to map a list of dict result

Time:07-28

I have an output like this:

[{'label': 'LABEL_0', 'score': 0.9994072914123535}]

using this code to output the final sentiment analyse:

def _sentiment(t):
    res = classifier(t)
    if res[0]['label']=='LABEL_0':
        return "positive" 
    if res[0]['label']=='LABEL_1':
        return "neutral"
    else: 
        return "negative"

The code above works fine but I'd like to know if there's a better way to write the _sentiment function. By better way I mean, better performance and cleaner.

CodePudding user response:

Starting from Python 3.10 you can use match statements:

def _sentiment(t):
    res = classifier(t)
    match res[0]['label']:
        case  'LABEL_0':
            return "positive" 
        case 'LABEL_1':
            return "neutral"
        case _:
            return "negative"

CodePudding user response:

The below code can answer your question:

sentiments = {'LABEL_0': 'positive', 'LABEL_1': 'neutral'}

def _sentiment(t):
    res = classifier(t)
    key = res[0]['label']
    sentiment = sentiments.get(key, 'negative')
    return sentiment
  • Related