s = input("Enter a sentence: ")
emp = ""
vow = 0
for i in s:
if i.isspace() == False:
emp = emp+i
else:
for j in emp:
if j in 'aeiouAEIOU':
vow = vow+1
print("The number of vowels in", emp, "are", vow)
emp = ""
它只给出第一个单词的元音。
答案 0 :(得分:4)
您的代码无效,因为变量vow
永远不会重置为0.您应该为每个遇到的新单词重置它,否则它会打印字符串中元音的总数。
更好的解决方案是使用split()
代替isspace()
,因此词语会自动生成"分离。
然后,你可以迭代每个单词,并总结出作为元音的字母。
words = s.split()
for word in words:
vow = sum(letter in 'aeiou' for letter in word.lower())
print("The number of vowels in", word, "are", vow)
答案 1 :(得分:1)
将re
模块用于正则表达式。
import re
sentence = r'Hello World, how many vowels are in this sentence by word?'
for word in sentence.split():
s = re.findall(r'[aeiou]', word, flags=re.IGNORECASE)
print(word,'has',len(s),'vowels.')
答案 2 :(得分:0)
您可以使用sum
或len
个功能。
>>> s="asdf 14oji iii34"
>>> sum(1 for i in s if i in 'aeiouAEIOU')
6
>>>
或
>>> len([i for i in s if i in 'aeiouAEIOU'])
6
>>>
答案 3 :(得分:0)
您也可以这样做:
sentence = input("Enter a sentence: ")
vowels = "aeiouAEIOU"
for word in sentence.split():
vowel_count = 0
for letter in word:
if letter in vowels:
vowel_count += 1
print("The number of vowels in %s is: %d" % (word, vowel_count))