要求:
写一个程序,计算句子中每个单词中某个字符出现的次数。
注意: 我们将英文字母的大小写当作同一个字符。例如,如果一个单词中同时包含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]
代码:
def count_char_occurrences(sentence, char):
sentence = sentence.lower()
counts = []
word = sentence.split()
for i in word:
count = i.count(char)
counts.append(count)
return counts
# 获取输入
sentence_input = input()
char_input = input()
# 调用函数
print(count_char_occurrences(sentence_input, char_input))