如何计算一个字符串中的元音

327 阅读4分钟

问题的提出和解决方案概述

在这篇文章中,你将学习如何计算一个字符串中元音的数量

为了使它更有趣,我们有以下的运行方案。

在加拿大,我们有一个叫萨斯喀彻温的省份。这个省有大量的平地。在这篇文章中,我们参考他们当地的说法。

💬 问题是。我们如何编写Python代码来计算一个字符串中的元音?

我们可以通过以下方法之一来完成这项任务。


在每个代码片断的顶部添加以下代码。这个代码段将使本文中的代码能够无误地运行。

import re
from collections import Counter

方法1:使用Regex和Dictionary Comprehension

这个例子使用 RegexDictionary Comprehension作为一个单行代码来统计一个字符串中指定元音的数量。结果以Dictionary格式返回。

saying = 'Saskatchewan! Where you can watch your dog run away for 3 days.'
vcount = {x: len(re.findall(f"{x}", saying.lower())) for x in 'aeiou'}
print(vcount)

⭐Finxter的最爱!

这段代码声明了字符串saying 。然后,Dictionary Comprehension将该字符串转换为小写字母,并且 re.findall()搜索并统计每个指定的元音。

结果保存到vcount ,并输出到终端。

输出

{'a': 8, 'e': 3, 'i': 0, 'o': 4, 'u': 3}

方法2:使用列表理解和count()

这个例子使用List Comprehension来统计一个字符串中指定元音的数量。结果以列表格式返回。

saying = 'Saskatchewan! Where you can watch your dog run away for 3 days.'
vcount = [saying.lower().count(x) for x in 'aeiou']
print(vcount)

这段代码声明了字符串saying 。然后,List Comprehension将字符串转换为小写字母,搜索并统计每个指定的元音。

结果保存在变量vcount ,并输出到终端。

输出

[8, 3, 0, 4, 3]

💡注意:这个输出显示的是总数,而不是相关的元音。


方法3:使用Counter()和count.update()。

这个例子调用Collections库并使用 Counter()来计算一个字符串中指定元音的数量。

saying = 'Saskatchewan! Where you can watch your dog run away for 3 days.'
count  = Counter()

for i in saying:
    if i in 'aeiou':
          count.update(i.lower())          
print(dict(count))

这段代码声明了字符串saying ,并启动了 Counter()对象,count

A [for](https://blog.finxter.com/python-loops/)循环实例化并遍历每个转换为小写的字符,搜索并统计每个指定元音。

结果保存到count ,并输出到终端。

如果这段代码使用print(count) ,输出到终端,则输出结果如下。

输出 使用print(count)

Counter({'a': 8, 'o': 4, 'e': 3, 'u': 3})

count 放在 [dict()](https://blog.finxter.com/python-dict/)删除单词Counter 和周围的大括号()

输出使用print(dict(count))

{'a': 8, 'e': 3, 'i': 0, 'o': 4, 'u': 3}

💡**注意:**该方法产生的输出与方法1相同,但多了四(4)行代码。


方法4:使用For和count()

这个例子使用了一个 for循环和 string.count()来统计一个字符串中指定元音的数量。结果以一个字符串的形式返回。

saying = 'Saskatchewan! Where you can watch your dog run away for 3 days.'
tmp = ''
for i in 'aeiou':
    tmp += i + ':' + str(saying.count(i)) + ' '
print(tmp)

这段代码声明了字符串saying ,并启动了一个变量tmp

A [for](https://blog.finxter.com/python-loops/)循环实例化并遍历每个字符,搜索并统计每个指定元音。结果转换为一个字符串,保存到tmp ,并输出到终端。

输出

a:8 e:3 i:0 o:4 u:3

方法5:使用 map() 和 count()

这个例子使用 map()count() 来统计一个字符串中指定元音的数量。

saying = 'Saskatchewan! Where you can watch your dog run away for 3 days.'
print(*map(saying.lower().count, 'aeiou'))

这段代码声明了字符串,saying ,将字符串转换为小写字母,并对指定的元音进行统计。结果被输出到终端。

输出

8 3 0 4 3

总结

在这个例子中。 lower()是不需要的,因为你可以看到没有元音是大写的。然而,你可能并不总是知道一个字符串将包含什么。在这种情况下,最好转换为小写或大写。

这五(5)种计算字符串中元音的方法应该给你足够的信息来选择适合你编码要求的最佳方法。

祝您好运,编码愉快!