由于某些原因,此代码不起作用:
def pyglatin(word):
output = ""
wordlenedit = len(word)-1
wordlen = len(word)
fixer = 0
while fixer == 0:
for i in word:
if i == 'a' or i == 'e' or i == 'o' or i == 'i' or i == 'u':
fixer = 1
else:
wordlenedit -= 1
else:
output = word[wordlenedit:wordlen:1] + '-' + word[0:wordlenedit:1] + 'ay'
return output
要查看问题,请单击here。问题似乎是它跳过了识别元音的if语句,但我不确定原因。这会导致一些非常奇怪的输出。在
您的函数不起作用,因为您遍历单词,从
wordlenedit = len(word)-1
开始,减少遇到的每个辅音的拆分索引。在在
for
循环的末尾,wordlenedit
等于(length of the word) - 1 - (number of consonants)
。只有当单词中第一个元音索引(从0开始)等于元音数目-1时,函数才有效。在另外,
while
循环在这里是无用的,因为您在for
循环中遍历整个单词。更糟糕的是:如果你有一个没有元音的单词,while
循环将是一个无限循环(比如“fly”,因为你没有检查“y”)这是您函数的更正版本,使用关键字break:
但是,可以用更简洁/简单的方式编写此函数,使用Regular Expressions,如下所示:
^{pr2}$如果要在不使用正则表达式的情况下执行此操作,最简单的方法是使用
enumerate
:相关问题 更多 >
编程相关推荐