Pig Latin Program in Python

筅森魡賤 提交于 2021-01-29 06:01:52

问题


Write a program in Python 3 that converts a sentence typed in by the user to Pig Latin. Pig Latin has two rules:

If a word begins with a consonant all consonants before the first vowel are moved to the end of the word and the letters "ay" are then added to the end. e.g. "coin" becomes "oincay" and "flute" becomes "uteflay". If a word begins with a vowel then "yay" is added to the end. e.g."egg" becomes "eggyay" and "oak" becomes "oakyay".

My code works for individual words but does not work for sentence. I have tried entering:

wordList = word.lower().split(" ")
    for word in wordList:

but it does not work.

#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 input sentence: the rain in Spain

The output sentence: ethay ainray inyay ainSpay


回答1:


So you could do something like this, it returns an iterable of all the pig-ed words and you can join them in the last step. You don't need that last return you have. My guess is the issue you saw was that you are returning in the first loop. you could track the return outside the loop and append to it in the loop and return that also.

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


来源:https://stackoverflow.com/questions/54079026/pig-latin-program-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!