Python 计算函数中的元音
我只是需要一个计算元音的函数的帮助,这个函数用来返回元音多于辅音的单词列表Python 计算函数中的元音,python,list,for-loop,function,Python,List,For Loop,Function,我只是需要一个计算元音的函数的帮助,这个函数用来返回元音多于辅音的单词列表 def moreVowels(text): vowels = 'AEIOUaeiou' words = text.split() returnList = [] for word in words: vowelCount = 0 for letter in word: if letter in vowels:
def moreVowels(text):
vowels = 'AEIOUaeiou'
words = text.split()
returnList = []
for word in words:
vowelCount = 0
for letter in word:
if letter in vowels:
vowelCount += 1
if vowelCount > len(word)/2:
returnList.append(word)
return returnList
mlk = 'Our lives begin to end the day we become silent about things that matter'
print(moreVowels(mlk))
当我打印函数时,它返回两次单词,不知道为什么
['Our','Our','about','about']
正如您发布的一样,它工作正常。但是,如果我改变元音count
if
语句的缩进,如下所示:
def moreVowels(text):
vowels = 'AEIOUaeiou'
words = text.split()
returnList = []
for word in words:
vowelCount = 0
for letter in word:
if letter in vowels:
vowelCount += 1
if vowelCount > len(word)/2: #indent changed
returnList.append(word) #indent changed
return returnList
我得到的结果和你一样。检查源代码中的缩进,记住不要混合制表符和空格。似乎没问题,您如何调用该方法?事实上,
mlk
var没有一个Our
单词,因此您做了一些错误的事情,或者只是一个拼写错误。您还可以将元音减少为一个大小写(例如,降低)用元音中的if-letter.lower()替换元音中的if-letter.lower()“--这只是一个ideaNote,您的returnList.append(word)
行不会像应该的那样缩进。这通常是一种混合制表符和空格的迹象,这可能会导致对行实际缩进深度的混淆。如果你的If-vouelcount>len(word)/2:returnList.append(word)
实际上(不仅仅是在外观上)缩进了一级,那就是你得到的输出(排印除外)。尝试使用python-tt yourprogramname.py运行程序进行检查。“out”是一个类型错误。我打印的方式是:打印(更多元音(mlk))