py有关函数与字典的问题

article = '''This is a photograph of our village.
Our village is in a valley.
It is between two hills.
The village is on a river.
Here is another photograph of the village.
My wife and I are walking along the banks of the river.
We are on the left.
There is a boy in the water.
He is swimming across the river.
Here is another photograph.
This is the school building.
It is beside a park.
The park is on the right.
Some children are coming out of the building.
Some of them are going into the park.
'''
def get_word_count(article):
  count = {}
  word_list=article.lower().replace('.','').split()
  for word in word_list:
    if word in count:
      count[word] += 1
    else:
      count[word] = 1
  return count
print(get_word_count(article))

为啥定义的空字典但是在执行if语句时字典中已经有了内容呢?

各位大神求解!!!

   else:中不就是   count[word] = 1 对字典添加属性了么

 

    if word in count:

      count[word] += 1

    else:

      count[word] = 1

这个if---else的意思就是:

如果 word的值 在 count字典中,

则count字典的word值的属性增加1

否则就给 count字典中添加一个word值的属性并赋值为1。

 

if---else是在for循环中重复执行的。

当某个word值第一次出现时是,给字典中添加一个属性。

当这个word值再次出现时,字典中就已经有了这个属性,就对这个属性增加1。

 

def get_word_count(article):
  count = {}
  word_list=article.lower().replace('.','').split()
  for word in word_list:
    if word in count.keys():
      count[word] += 1
    else:
      count[word] = 1
  return count
print(get_word_count(article))

其实就只需要将 `if word in count` 改成 `if word in count.keys()` 即可

您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632

非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!

速戳参与调研>>>https://t.csdnimg.cn/Kf0y