使用字典统计输入字符串中字母的频率。只应计算字母,而不应计算空格、数字或标点符号。应将大写字母视为与小写字母相同。例如,count_letters(“这是一个句子。”)应返回{'t':2,'h':1,'i':2,'s':3,'a':1,'e':3,'n':2,'c':1}
def count_letters(text):
result = {}
# Go through each letter in the text
for letter in text:
# Check if the letter needs to be counted or not
if letter not in result:
result[letter.lower()] = 1
# Add or increment the value in the dictionary
else:
result[letter.lower()] += 1
return result
print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}
print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}
print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}发布于 2021-02-27 22:25:44
可以使用.isalpha()方法检查字符是否为字母。
然后使用.get方法返回特定键的值。
def count_letters(text):
result = {}
# Go through each letter in the text
for letter in text.lower():
# Check if the letter needs to be counted or not
if(letter.isalpha()):
result[letter] = result.get(letter,0)+1
# Add or increment the value in the dictionary
return resulthttps://stackoverflow.com/questions/60941943
复制相似问题