【问题标题】:How can I use the split() function to figure out how many vowels there are in total?如何使用 split() 函数来计算总共有多少个元音?
【发布时间】:2021-05-22 08:14:32
【问题描述】:

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

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

umm.... counter 不工作了伙计们..(我的意思是我想让你一一给我细节,而不是基本 Python 的内置函数,以便它可以在其他编码程序上工作。

【问题讨论】:

  • 这显示了字符串中出现了多少 a。它的作用:它在每个“a”上拆分字符串,然后计算返回的数组的长度。 x = len(txt.split("a"))

标签: python function printing split sentence


【解决方案1】:

我建议使用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

【讨论】:

  • 感谢您的回答,但我在 RUR-PLE 工作,所以计数器不工作......还有其他方式吗?
【解决方案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)

【讨论】:

    猜你喜欢
    • 2018-03-17
    • 2021-08-21
    • 1970-01-01
    • 2015-07-10
    • 2020-07-28
    • 1970-01-01
    • 2021-02-11
    • 2013-12-20
    • 1970-01-01
    相关资源
    最近更新 更多