如何在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.