计算字符串中单词中的元音数量

counting the number of vowels in a word in a string

我是初学者,我想找出字符串中每个单词的元音数量。因此,例如,如果我有 "Hello there WORLD",我想获得 [2, 2, 1].

的输出

哦,我正在使用 Python。

目前我有这个

[S.count(x) in (S.split()) if x is 'AEIOUaeiou']

其中 S="Hello there WORLD"

但是一直报错。有什么提示吗?

x is 'AEIOUaeiou'

这将测试 x 是否与 'AEIOUaeiou' 完全相同。当您比较对象时,这几乎不是您想要的。例如以下可能是 False:

>>> a = 'Nikki'
>>> b = 'Nikki'
>>> a is b
False

不过,它可能是 True,因为有时 Python 会优化相同的字符串以实际使用相同的对象。

>>> a == b
True

这将始终是 True,因为比较的是 ,而不是对象的 身份

您可能想要的是:

x in 'AEIOUaeiou'

很明显,S.count中的S和S.split中的S不可能是同一个S,我建议多使用语义名称。

>>> phrase = 'Hello there WORLD'
>>> [sum(letter.casefold() in 'aeiouy' for letter in word) for word in phrase.split()]
[2, 2, 1]