Python的Pig Latin程序 [英] Pig Latin Program in Python

查看:90
本文介绍了Python的Pig Latin程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3中编写一个程序,将用户键入的句子转换为Pig Latin.猪拉丁语有两个规则:

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

如果单词以辅音开头,则第一个辅音之前的所有辅音将元音移到单词的末尾,然后将字母"ay"移到添加到最后.例如硬币"变成"Oincay",长笛"变成"uteflay".如果单词以元音开头,则将"yay"添加到结尾.例如,鸡蛋"变成"eggyay",橡木"变成"oakyay".

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:

但它不起作用.

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

输入句子:西班牙的雨

输出句子: ethay ainray inyay ainSpay

推荐答案

因此,您可以执行以下操作,它返回所有可重复使用的单词的可迭代形式,您可以在最后一步将它们加入.您不需要最后的回报.我的猜测是您看到的问题是您要在第一个循环中返回.您可以在循环外部跟踪返回值,并在循环中追加返回值,也可以返回.

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

这篇关于Python的Pig Latin程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆