36.单词表问题 小明是一名学生,他正在学习英语单词的拼写。他想要创建一个单词表,用于存储他学习过的单词,并统计每个单词出现的次数。请你帮助他补全代码完成以下任务: (1)创建一个空的字典 word_dict,用于存储单词和对应的出现次数; (2)使用 input() 函数,提示小明输入一个单词,并将其存储到变量 word 中; (3)检查字典 word_dict 中是否已经存在该单词。如果存在,则将该单词的出现次数加一;如果不存在,则将该单词添加到字典中,并将其出现次数设置为一; (4)重复步骤 2 和步骤 3,直到小明输入字符串's'为止; (5)创建一个空的集合 unique_words,用于存储所有不重复的单词; (6)遍历字典 word_dict 的键(即单词),将每个键添加到集合 unique_words 中; (6)打印出字典 word_dict 中每个单词和对应的出现次数; (8)打印出集合 unique_words 中的所有不重复的单词。 样例: 输入 请输入一个单词:hello 请输入一个单词:world 请输入一个单词:hello 请输入一个单词:python 请输入一个单词:s 输出 单词和出现次数: hello : 2 world : 1 python : 1 不重复的单词: world hello python 程序: word_dict = {} while True: word = input("请输入一个单词:") if word == "s": break if word in word_dict: ① else: word_dict[word] = 1 unique_words = ② for word in word_dict: unique_words.add(word) print("单词和出现次数:") for word in word_dict: ③ print("不重复的单词:") for word in unique_words: ④
使用微信搜索喵呜刷题,轻松应对考试!
答案:
1. 创建一个空的字典 word_dict,用于存储单词和对应的出现次数:```pythonword_dict = ```2. 使用 input() 函数,提示小明输入一个单词,并将其存储到变量 word 中:```pythonwhile True:word = input("请输入一个单词:")```3. 检查字典 word_dict 中是否已经存在该单词。如果存在,则将该单词的出现次数加一;如果不存在,则将该单词添加到字典中,并将其出现次数设置为一:```pythonif word == "s":breakif word in word_dict:word_dict[word] += 1else:word_dict[word] = 1```4. 创建一个空的集合 unique_words,用于存储所有不重复的单词:```pythonunique_words = set()```5. 遍历字典 word_dict 的键(即单词),将每个键添加到集合 unique_words 中:```pythonfor word in word_dict:unique_words.add(word)```6. 打印出字典 word_dict 中每个单词和对应的出现次数:```pythonprint("单词和出现次数:")for word, count in word_dict.items():print(f"word : count")```7. 打印出集合 unique_words 中的所有不重复的单词:```pythonprint("不重复的单词:")for word in unique_words:print(word)```