小编Sey*_*yiA的帖子

这个字典中的for循环如何正常工作?

目前我正在通过这个在线课程学习Python文本情感模块,讲师没有详细解释这段代码是如何工作的.我试着单独搜索每一段代码,试着拼凑他是怎么做的,但这对我来说毫无意义.

  1. 那么这段代码是如何工作的呢?为什么字典括号中有for循环?

  2. 什么是背后的逻辑x之前,for y in emotion_dict.values()那么for x in y在结束了吗?

  3. emotion_dict=emotion_dict括号内的目的是什么?不emotion_dict会这样做吗?

     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
    
    Run Code Online (Sandbox Code Playgroud)

python dictionary python-3.x set-comprehension

2
推荐指数
1
解决办法
77
查看次数