gpt4 book ai didi

Python Pig Latin 转换器(以辅音开头的单词)

转载 作者:行者123 更新时间:2023-12-01 09:12:51 24 4
gpt4 key购买 nike

我正在尝试将字符串转换为 pig 拉丁语。网上的大多数示例都没有考虑到如果一个单词以多个辅音开头,则必须将所有辅音移到末尾(school --> oolschay)。我的版本目前正在使用第一个字母作为元音以及抓取那些不以元音开头的单词,但是,我不知道如何阻止它抓取单词中元音的每个实例而不是只是第一个例子。

这是代码:

pigLatin = input("Convert message to pig latin: ")
wordList = pigLatin.lower().split(" ")
vowels = ['a', 'e', 'i', 'o', 'u']
pigLatin = []
eachWord = []
for word in wordList:
if word[0] in 'aeiou': #case where vowel is first
pigLatin.append(word + 'yay')
if word[0] not in 'aeiou':
for letter in word:
if letter in 'aeiou':
pigLatin.append(word[word.index(letter):] + word[:word.index(letter)] +'ay')


print(" ".join(pigLatin))

最佳答案

您可以在内部 for 循环中添加一个 break 语句来迭代每个单独的单词。一旦找到元音,它就会跳出循环。或者至少我认为这就是您遇到的问题(您的问题有点令人困惑。)

试试这个:

pigLatin = input("Convert message to pig latin: ")
wordList = pigLatin.lower().split(" ")
vowels = ['a', 'e', 'i', 'o', 'u']
pigLatin = []
eachWord = []
for word in wordList:
if word[0] in 'aeiou': #case where vowel is first
pigLatin.append(word + 'yay')
else:
for letter in word:
if letter in 'aeiou':
pigLatin.append(word[word.index(letter):] + word[:word.index(letter)] +'ay')
break


print(" ".join(pigLatin))

我还通过放置 else 而不是 if word[0] not in 'aeiou':

让您的代码风格变得更好一点

编码愉快!

关于Python Pig Latin 转换器(以辅音开头的单词),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51508664/

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