gpt4 book ai didi

python - 无法在 pig 拉丁语翻译器中将 y 转换为元音词(即健身房)

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:38 25 4
gpt4 key购买 nike

我从编程开始,自学 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'

关于python - 无法在 pig 拉丁语翻译器中将 y 转换为元音词(即健身房),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33005290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com