python - 如何在 Python 中计算元音和辅音
问题描述
我正在尝试编写一个程序,该程序接受用户输入的句子并在 python 中输出元音和辅音的计数。我的元音计数器工作没有任何问题,但辅音计数总是返回 0。我不知道为什么。
def checkvowelsConsonants():
consonants = 0
vowelscount = 0
index = 0
sentence = input("Please input your sentence here. This sentence must contain a speical character eg, - ? etc.")
Vowels = (["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"])
vowelcount = 0
while index < len(sentence):
if sentence[index] in Vowels:
vowelcount += 1
index += 1
while index < len(sentence):
if sentence[index] not in Vowels:
consonants += 1
index += 1
print("The number of vowels is", vowelcount, "and consonants is", consonants)
这是我收到的参考输出
请在此处输入您的句子。这句话必须包含一个特殊字符,例如 - ? etc.aaaaaaasssssssssss 元音数为 8,辅音数为 0
解决方案
def classify_letter(string: str):
vowels = 0
consonants = 0
for i in string:
if i.casefold() in 'aeiou':
vowels += 1
elif i.casefold() in 'qwrtypsdfghjklzxcvbnm':
consonants += 1
return vowels, consonants
或列表理解
def classify_letter(strng: str) -> tuple:
x = [i.casefold() in "aeiou" for i in strng if i.casefold() in string.ascii_lowercase]
return x.count(True), x.count(False)
^ 我承认这可能不是实现它的最佳方式,我愿意接受建议以使其更短和优化!
当通过"hello-"
这两个返回时:
(2,3)
推荐阅读
- java - 如何使用 MyBatis 将作为 Java 保留字的 DB 列名映射到 Java 模型对象字段?
- ruby-on-rails - Ruby PayPal 权限 SDK Gem
- python - `np.any` returns an object from an object array instead of boolean?
- javascript - 当应用程序在后台时,Electron 使用条形码扫描仪
- maven - Maven 只为子模块增加版本
- uml - UML 中关联的主题/语义标记
- yii - Yii2 data-* 属性未使用 GridView 列呈现
- python - 没有名为 pandas 的模块,但 pandas 已安装在 linux 中
- mysql - MySql 查询以获取具有子查询值之一的列的行
- javascript - Redux 形式的异步数据加载