首页 › Python 实例 › 统计元音字母

Python 统计元音字母

字符串实例 022

题目

统计英文句子中元音字母(a、e、i、o、u)的数量,并找出包含元音最多的单词。

参考代码

sentence = "Programming in Python is an enjoyable experience"
vowels = set("aeiou")

count = sum(1 for ch in sentence.lower() if ch in vowels)
print("元音字母总数:", count)

best = max(sentence.split(), key=lambda w: sum(ch in vowels for ch in w.lower()))
print("元音最多的单词:", best)
执行以上代码输出结果为:
元音字母总数: 16
元音最多的单词: experience

代码解析

把元音放进集合,成员判断更快。max() 的 key 参数指定比较依据,这里按每个单词中元音的数量比较。布尔值相加时 True 视为 1。