【问题标题】:Pig Latin Program in PythonPython中的猪拉丁程序
【发布时间】:2019-01-07 17:25:42
【问题描述】:

用 Python 3 编写一个程序,将用户输入的句子转换为 Pig Latin。猪拉丁有两条规则:

如果单词以辅音开头,则第一个之前的所有辅音 元音移动到单词的末尾,然后字母“ay” 添加到最后。例如“硬币”变成“oincay”,“长笛”变成 “乌特弗莱”。如果单词以元音开头,则将“yay”添加到 结尾。例如,“egg”变成“eggyay”,“oak”变成“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

【问题讨论】:

    标签: python-3.x for-loop


    【解决方案1】:

    所以你可以做这样的事情,它返回所有猪词的迭代,你可以在最后一步加入它们。你不需要最后的回报。我的猜测是您看到的问题是您在第一个循环中返回。您可以跟踪循环外的返回并在循环中附加到它并返回。

    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)))
    

    【讨论】:

    • 中断是这样它只找到元音的第一个实例
    • 谢谢!我很感激。你能解释一下 print(' ' .join(pig_latin(word))) 吗?
    • pig_latin 返回一个可迭代对象。就像一个列表(有点),连接将迭代中的元素与" "
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多