Sey*_*yiA 2 python dictionary python-3.x set-comprehension
目前我正在通过这个在线课程学习Python文本情感模块,讲师没有详细解释这段代码是如何工作的.我试着单独搜索每一段代码,试着拼凑他是怎么做的,但这对我来说毫无意义.
那么这段代码是如何工作的呢?为什么字典括号中有for循环?
什么是背后的逻辑x之前,for y in emotion_dict.values()那么for x in y在结束了吗?
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)该行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)
Run Code Online (Sandbox Code Playgroud)
在x之后的权利{在原有的一套理解意味着在集合存储的参数值.总而言之,emotions它只是字典中所有容器中所有元素的集合(没有重复)emotion_dict.尝试打印出来emotion_dict,并emotion和比较.
在函数定义中,
def emotion_analyzer(text, emotion_dict=emotion_dict):
Run Code Online (Sandbox Code Playgroud)
这emotion_dict=emotion_dict意味着如果你没有传递任何东西作为第二个参数,那么带有name 的局部变量emotion_dict将被设置为类似命名的全局变量emotion_dict.这是默认参数的示例.
| 归档时间: |
|
| 查看次数: |
77 次 |
| 最近记录: |