sentence = "to be or not to be that is a question"

将字符串按空格分割成单词列表

words = sentence.split()

创建一个空字典用于存储单词出现的次数

word_count = {}

遍历单词列表,统计每个单词出现的次数

for word in words: if word in word_count: word_count[word] += 1 else: word_count[word] = 1

输出统计结果

print(word_count)

实现统计字符串中的单词和单词出现的次数:要求如下:1统计的语句为:to be or not to be that is a question2要求统计该句中出现的所有单词和其出现次数。3使用字典进行输出格式如下注意:排列顺序可以不一致但是统计的次数要正确:to 2 be 2 or 1 not 1 is 1 a 1 question 1 that 1

原文地址: https://www.cveoy.top/t/topic/ibBo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录