【问题标题】:Python Pig Latin Converter (Words that start with consonants)Python Pig Latin 转换器(以辅音开头的单词)
【发布时间】:2018-07-24 22:58:10
【问题描述】:

我正在尝试将字符串转换为猪拉丁语。大多数在线示例都没有考虑到如果一个单词以多个辅音开头,则必须将所有辅音移到末尾(学校-> 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))

【问题讨论】:

  • 什么是猪拉丁语?
  • Here's an answer 我提出了一个非常相似的问题。要获得第一个 元音,只需将 not in 更改为 in
  • 另外,我认为您使用word.index 的方法对于以多个辅音开头的单词(例如llama)会失败
  • 他的word.index() 调用实际上不会失败,因为他使用它在第一个元音处分割字符串,所以它会寻找第一个元音 并将元音左侧的所有内容附加到pigLatin 的末尾。由于string.index() 获得了子字符串的第一个索引,而我们只想要第一个元音,所以他的代码很好。

标签: python python-3.x


【解决方案1】:

您可以在循环每个单词的内部 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': 使您的代码风格更好一些

编码愉快!

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多