编写一个程序,计算句子中每个单词中某个字符出现的次数。
注意: 我们将英文字母的大小写当作同一个字符。例如,如果一个单词中同时包含S和s,那么它们都将被计为同一个字母s的出现次数。
- 定义函数
count_char_occurrences()
,有两个参数:sentence
(句子)和char
(字符)。 - 在函数内部,将
sentence
转换为小写。 - 返回一个列表,包含
char
在句子的每个单词中出现的次数。
示例输入
She sells sea shells by the seashore. s
示例输出
[1, 2, 1, 2, 0, 0, 2]
本题涉及字符串分割、大小写转换、计数函数。
字符串分割用str.split(''),按照该字符进行分割。
大小写转换,str.upper()小写转换为大写,str.lower()大写转换为小写。
计数用str.count(ch),返回str字符串中ch出现的次数。
def count_char_occurrences(sentence, char):
# 此处编写你的代码
result=[]
for word in sentence.lower().split(' '):
result.append(word.count(char))
return result
# 获取输入
sentence_input = input()
char_input = input()
# 调用函数
print(count_char_occurrences(sentence_input, char_input))