1.
简答题
实现统计字符串中的单词和单词出现的次数:
要求如下:
(1)统计的语句为:to be or not to be that is a question
(2)要求统计该句中出现的所有单词和其出现次数。
(3)使用字典进行输出,格式如下(注意:排列顺序可以不一致,但是统计的次数要正确):
{'to': 2, 'be': 2, 'or': 1, 'not': 1, 'is': 1, 'a': 1, 'question': 1, 'that': 1}
查看答案与解析
答案:<p>参考程序:</p><pre class="brush:python;toolbar:false">string = "to be or not to be that is a question"#定义变量存储字符串
lis=string.split(" ")#使用分割函数将字符串转为列表
count={}#定义一个空字典
for x in lis:#遍历列表
if x not in count:#判断列表元素是否在字典中
count[x]=1
else:
count[x]+=1
print(count)#打印字典</pre><p><br/></p>
解析:
评分标准:
(1)能正确存储字符串; (2分)
(2)能使用分割函数将字符串转为列表(或者其他序列及可迭代对象均可); (3分)
(3)创建字典;(2分)
(4)有循环遍历列表(或迭代对象); (3分)
(5)判断列表(或可迭代对象)元素是否在字典中;( 3分)
(6)输出格式正确; (2分)
(7)代码执行完全正确无误。(5分)
本题需要用到字符串的基本操作,字典,条件判断,循环等知识。