Currently I'm learning Python text sentiment module via this online course and the lecturer failed to explain in enough detail how this piece of code works. I tried searching each piece of code individually to try piece together how he did it but it makes no sense to me.
So how does this code work? Why is there a for loop within dictionary braces?
What is the logic behind
x
before thefor y in emotion_dict.values()
thenfor x in y
at the end?What is the purpose behind
emotion_dict=emotion_dict
within the parentheses? Wouldn't justemotion_dict
do?def emotion_analyzer(text,emotion_dict=emotion_dict): #Set up the result dictionary emotions = {x for y in emotion_dict.values() for x in y} emotion_count = dict() for emotion in emotions: emotion_count[emotion] = 0 #Analyze the text and normalize by total number of words total_words = len(text.split()) for word in text.split(): if emotion_dict.get(word): for emotion in emotion_dict.get(word): emotion_count[emotion] += 1/len(text.split()) return emotion_count