2017-10-28 102 views
2

目前我正在通过这个在线课程学习Python文本情感模块,讲师未能详细解释这段代码是如何工作的。我试着单独搜索每段代码,试图拼凑出他是如何做到的,但对我来说没有意义。本字典中的for循环是如何工作的?

  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 
    
+0

'emotion_dict = emotion_dict'给该函数一个默认值,如果没有提供值,将会使用该默认值。 –

回答

5

1和2

线emotions = {x for y in emotion_dict.values() for x in y}使用集理解。它建立了一个集合,而不是一本字典(虽然字典解析也存在,看起来有点相似)。这是

emotions = set() # Empty set 
# Loop over all values (not keys) in the pre-existing dictionary emotion_dict 
for y in emotion_dict.values(): 
    # The values y are some kind of container. 
    # Loop over each element in these containers. 
    for x in y: 
     # Add x to the set 
     emotions.add(x) 

x速记符号在原设定修真{之后表示在设定存储的参数值。总而言之,emotions只是字典emotion_dict中所有容器内所有元素的集合(不重复)。尝试打印出emotion_dictemotion并进行比较。

在函数的定义,

def emotion_analyzer(text, emotion_dict=emotion_dict): 

emotion_dict=emotion_dict当地变量名称为emotion_dict被设置为全球变量类似命名emotion_dict,如果你不及格任何事都是第二个参数。这是一个default argument的示例。

+0

感谢您的回应,现在我有意识地提高了理解力。感谢各部分的明确分解。 – SeyiA