如何使用 split() 函数计算出总共有多少个元音字母?

How can I use the split() function to figure out how many vowels there are in total?

如何使用 split() 函数计算出总共有多少个元音字母? 如何在每个句子中打印 a、e、i、o 和 u 的数量? 句子是

'I study Python programming at KAIST Center For Gifted Education'

umm.... counter is not working guys..(我的意思是我想让你一一给我详细信息,而不是基本的内置函数 Python,这样它就可以在其他编码程序上工作。


我建议使用 collections.Counter(),例如像这样:

from collections import Counter

sentence = 'I study Python programming at KAIST Center For Gifted Education'

counts = Counter(sentence)

print(counts['a'])
# 3
print(counts['A'])
# 1
print(counts['e'])
# 3
print(counts['E'])
# 1
print(counts['i'])
# 3
print(counts['I'])
# 2
print(counts['o'])
# 4
print(counts['O'])
# 0
print(counts['u'])
# 2
print(counts['U'])
# 0

如果您想独立地计算元音,您可以在将句子传递给 Counter() 之前调用 .lower(),例如:

from collections import Counter

sentence = 'I study Python programming at KAIST Center For Gifted Education'

counts = Counter(sentence.lower())

print(counts['a'])
# 4
print(counts['e'])
# 4
print(counts['i'])
# 5
print(counts['o'])
# 4
print(counts['u'])
# 2

编辑:

如果由于某种原因您无法使用集合库,字符串有一个 count() 方法:

sentence = 'I study Python programming at KAIST Center For Gifted Education'

print(sentence.count('a'))
# 3
print(sentence.count('e'))
# 3
print(sentence.count('i'))
# 3
print(sentence.count('o'))
# 4
print(sentence.count('u'))
# 2

如果您想要计算的不仅仅是元音,“手动”计算子字符串(即您的情况下的元音)可能更有效,例如:

sentence = 'I study Python programming at KAIST Center For Gifted Education'

# Initialise counters:
vowels = {
    'a': 0,
    'e': 0,
    'i': 0,
    'o': 0,
    'u': 0,
}

for char in sentence:
    if char in vowels:
        vowels[char] += 1

print(vowels['a'])
# 3
print(vowels['e'])
# 3
print(vowels['i'])
# 3
print(vowels['o'])
# 4
print(vowels['u'])
# 2

检查这个?

from collections import Counter
x='I study Python programming at KAIST Center For Gifted Education'
x=[a for a in x]
vowels=['a','e','i','o','u']
check_list=[]
for check in x:
    if check.lower() in vowels:
        check_list.append(check.lower())
count=Counter(check_list)
print(count)