我从编程开始,自学 Python 3.4.3。我有一个关于 pig 拉丁语翻译器的问题(似乎是每个人最喜欢编写的程序,并提出问题)。
我的代码似乎工作正常,除非我写了一个只有 y 作为其中唯一元音的单词。
def pig_latin(word):
print(word)#test
if word[0] in 'bcdfghjklmnpqrstvwxyz':
i = 0
print(word[i]) #test
while word[i] in 'bcdfghjklmnpqrstvwxyz':
i += 1
word = word[i:] + word[:i] + 'ay'
elif word[0] in 'aeiou':
word += 'way'
return word
def main():
sentence = input('Enter a phrase to convert to pig latin: ')
word = ''
pig_sentence = ''
i = 0
for i in range(len(sentence)):
if sentence[i] != ' ':
word += sentence[i]
else:
pig_sentence += pig_latin(word) + ' '
word = ''
pig_sentence += pig_latin(word)
print(pig_sentence)
if __name__ == '__main__':
main()
我收到的错误与这行代码有关:
while word[i] in 'bcdfghjklmnpqrstvwxyz':
错误是:IndexError: string index out of range
在玩了很多东西之后,我有点难过。任何帮助将不胜感激。
请您参考如下方法:
您的问题是单词中没有元音。如果没有元音字母,则以下 while 循环永远不会停止,您会得到一个 IndexError:
while word[i] in 'bcdfghjklmnpqrstvwxyz':
i += 1
word = word[i:] + word[:i] + 'ay'
要解决这个问题,请检查 i 是否小于单词的长度:
while i < len(word) and word[i] in 'bcdfghjklmnpqrstvwxyz':
i += 1
word = word[i:] + word[:i] + 'ay'
现在有了这个实现,第一个字符不会移动到单词的末尾(即 gym 变成 gymay),所以为此写一个条件:
while i < len(word) and word[i] in 'bcdfghjklmnpqrstvwxyz':
i += 1
if i == len(word):
i = 1
word = word[i:] + word[:i] + 'ay'
