在Python 3中编写一个程序,将用户键入的句子转换为Pig Latin。拉丁猪有两个规则:
如果单词以辅音开头,则所有辅音在第一个辅音之前 将元音移至单词的末尾,然后将字母“ ay”移至 添加到最后。例如“硬币”变成“ Oincay”,“长笛”变成 “ uteflay”。如果单词以元音开头,则将“ yay”添加到 结束。例如,“鸡蛋”变成“ eggyay”,“橡木”变成“ oakyay”。
我的代码适用于单个单词,但不适用于句子。我尝试输入:
wordList = word.lower().split(" ")
for word in wordList:
但是它不起作用。
#Pig Latin Program
import sys
VOWELS = ('a', 'e', 'i', 'o', 'u')
def pig_latin(word):
if (word[0] in VOWELS):
return (word +"yay")
else:
for letter in word:
if letter in VOWELS:
return (word[word.index(letter):] + word[:word.index(letter)] + "ay")
return word
word = ""
while True:
word = input("Type in the word or Exit to exit:")
if (word == "exit" or word == "Exit" or word == "EXIT"):
print("Goodbye")
sys.exit()
else:
print(pig_latin(word))
输入句子:the rain in Spain
输出句子:ethay ainray inyay ainSpay
答案 0 :(得分:0)
因此,您可以执行以下操作,它返回所有带有单词的单词的可迭代内容,您可以在最后一步将它们加入。您不需要最后的回报。我的猜测是您看到的问题是您要在第一个循环中返回。您可以在循环外部跟踪返回值,并在循环中追加返回值,也可以返回。
import sys
VOWELS = ('a', 'e', 'i', 'o', 'u')
def pig_latin(word):
wordList = word.lower().split(" ")
for word in wordList:
if (word[0] in VOWELS):
yield (word +"yay")
else:
for letter in word:
if letter in VOWELS:
yield (word[word.index(letter):] + word[:word.index(letter)]+ "ay")
break
word = ""
while True:
word = input("Type in the word or Exit to exit:")
if (word == "exit" or word == "Exit" or word == "EXIT"):
print("Goodbye")
sys.exit()
else:
print(' '.join(pig_latin(word)))