Python 这个字典中的for循环究竟是如何工作的?
目前,我正在通过这门在线课程学习Python文本情感模块,但讲师没有足够详细地解释这段代码是如何工作的。我试着单独搜索每一段代码,试着把他是如何做到的,但这对我来说毫无意义Python 这个字典中的for循环究竟是如何工作的?,python,python-3.x,dictionary,set-comprehension,Python,Python 3.x,Dictionary,Set Comprehension,目前,我正在通过这门在线课程学习Python文本情感模块,但讲师没有足够详细地解释这段代码是如何工作的。我试着单独搜索每一段代码,试着把他是如何做到的,但这对我来说毫无意义 那么这个代码是如何工作的呢?为什么字典大括号中有for循环 在情绪指令值中y的之前的x后面的逻辑是什么 括号内的emotion\u dict=emotion\u dict的目的是什么?难道仅仅是情感不就可以了吗 def emotion_analyzer(text,emotion_dict=emotion_dict): #
之前的x
后面的逻辑是什么
emotion\u dict=emotion\u 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
emotions={x代表y在emotion_dict.values()代表y中的x}
使用一个集合。它构建的是一个集合,而不是一个字典(尽管字典的理解也存在并且看起来有些相似)。它是英语的简写符号
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
表示要存储在集合中的值。总之,情绪
只是一个集合(没有重复)字典中所有容器中的所有元素。请尝试打印emotion\u dict
和emotion
,然后进行比较
3.
在函数定义中
def emotion_analyzer(text, emotion_dict=emotion_dict):
emotion\u dict=emotion\u dict
表示,如果不将任何内容作为第二个参数传递,则名为emotion\u dict
的局部变量将设置为类似名为emotion\u dict
的全局变量。这是一个示例。emotion\u dict=emotion\u dict为函数提供默认值,如果未提供任何值,则将使用。感谢您的回复,现在我查看了set CONTRUMENT。感谢您对每个部分的清晰分解。