如何在Python中检测元音和辅音?


在英语字母表中,元音字母是a、e、i、o和u。包含元音的单词示例包括“apple”、“elephant”、“igloo”、“octopus”和“umbrella”。

辅音是英语字母表中的所有其他字母,包括b、c、d、f、g、h、j、k、l、m、n、p、q、r、s、t、v、w、x、y和z。包含辅音的单词示例包括“ball”、“cat”、“dog”、“fish”、“green”和“hat”。

以下是一些带有逐步说明的代码示例,用于在Python中检测元音和辅音

使用for循环和条件语句

示例

定义要检查元音和辅音的字符串。

将元音和辅音的计数器初始化为0。

循环遍历字符串中的每个字符。

检查字符的小写版本是否在字符串“aeiou”中。如果是,则递增元音计数器。

如果字符是字母但不是元音,则递增辅音计数器。

打印计数器的结果。

string = "lorem ipsum"
vowels = 0
consonants = 0
for char in string:
    if char.lower() in "aeiou":
        vowels += 1
    elif char.isalpha():
        consonants += 1
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

输出

Number of vowels: 4
Number of consonants: 6

使用列表推导和集合

示例

定义要检查元音和辅音的字符串。

使用列表推导创建字符串中所有小写元音字符的列表。

使用内置的len()函数获取列表中的项目数,即元音的个数。

使用另一个列表推导创建字符串中所有不是小写元音的字母字符的列表。

使用内置的len()函数获取列表中的项目数,即辅音的个数。

打印计数器的结果。

string = "lorem ipsum"
vowels = len([char for char in string if char.lower() in {'a', 'e', 'i', 'o', 'u'}])
consonants = len([char for char in string if char.isalpha() and char.lower() not in {'a', 'e', 'i', 'o', 'u'}])
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

输出

Number of vowels: 4
Number of consonants: 6

使用正则表达式

示例

导入内置的re模块,该模块提供对正则表达式的支持。

定义要检查元音和辅音的字符串。

使用re.findall()函数查找正则表达式模式“[aeiou]”的所有匹配项,该模式匹配任何小写元音,忽略大小写。

使用内置的len()函数获取匹配项的数量,即元音的个数。

使用re.findall()再次使用正则表达式模式“[b-df-hj-np-tv-z]”,该模式匹配任何小写辅音,忽略大小写。

再次使用len()获取匹配项的数量,即辅音的个数。

打印计数器的结果。

import re
string = "lorem ipsum"
vowels = len(re.findall("[aeiou]", string, re.IGNORECASE))
consonants = len(re.findall("[b-df-hj-np-tv-z]", string, re.IGNORECASE))

print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

输出

Number of vowels: 4
Number of consonants: 6

使用集合和交集

示例

定义要检查元音和辅音的字符串。

使用set()函数创建一个包含字符串中所有字符的集合,转换为小写。

使用set.intersection()方法查找此集合和小写元音集合之间的交集,并使用len()函数获取结果集合中的元素数量。

重复步骤3,但使用小写辅音集合。

打印计数器的结果。此处重复字符计为一个。

string = "lorem ipsum"
vowels = len(set(string.lower()).intersection({'a', 'e', 'i', 'o', 'u'}))
consonants = len(set(string.lower()).intersection(set('bcdfghjklmnpqrstvwxyz')))
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

输出

Number of vowels: 4
Number of consonants: 5

使用字典和字符串格式化

示例

定义要检查元音和辅音的字符串。

创建一个字典,其中键为“元音”和“辅音”,并将它们的初始值设置为0。

循环遍历字符串中的每个字符。

如果字符的小写版本在字符串“aeiou”中,则递增字典中的“元音”值。

如果字符是字母但不是元音,则递增字典中的“辅音”值。

使用字符串格式化打印字典中计数器的结果。

string = "lorem ipsum"

count = {'vowels': 0, 'consonants': 0}
for char in string:
    if char.lower() in 'aeiou':
        count['vowels'] += 1
    elif char.isalpha():
        count['consonants'] += 1
print("Number of vowels: {vowels}\nNumber of consonants: {consonants}".format(**count))

Output

Number of vowels: 4 Number of consonants: 6

使用Counter和filter

示例

从collections模块导入Counter类。

定义要检查元音和辅音的字符串。

使用filter()函数创建一个仅包含小写元音字符的新迭代器,并使用Counter()构造函数计算每个元音的出现次数。

将每个元音的计数相加以获得元音的总数。

重复步骤3-4,但过滤掉不是元音的字母字符,并使用sum()函数获取辅音的总数。

打印计数器的结果。

from collections import Counter
string = "lorem ipsum"
count = Counter(filter(lambda c: c.lower() in 'aeiou', string))
vowels = count['a'] + count['e'] + count['i'] + count['o'] + count['u']
count = Counter(filter(lambda c: c.isalpha() and c.lower() not in 'aeiou', string))
consonants = sum(count.values())
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

输出

Number of vowels: 4
Number of consonants: 6

更新于:2023年8月10日

3K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.