任务要求:编写一段代码,统计字符串中单词出现的次数,将字符串及次数存储在字典中,打印实现以下效果 知识点:字符串的分割、字典
参考答案:
# coding=utf-8
"""
Author: 笨笨
Date: 2020-12-23
"""
# 定义字典
# key:字符串,value:次数
dict_1 = {}
str_1 = "Welcome to BenBen's home. Welcome to Python. But which Python version should I use? Python 2 or Python 3?"
for wd in str_1.split():
# 如果键不存在,添加字典元素,值为1
if wd not in dict_1:
dict_1[wd] = 1
# 字典键存在,值加1
else:
dict_1[wd] += 1
for key, value in dict_1.items():
print("{}: {}".format(key, value))