1
VOWELS = ('a', 'e', 'i', 'o', 'u')


def pigLatin(word):
    first_letter = word[0]
    if first_letter in VOWELS:  # if word starts with a vowel...
        return word + "hay"     # then keep it as it is and add hay to the end
    else:
        return word[1:] + word[0] + "ay"


def findFirstVowel(word):
    novowel = False
    if novowel == False:
        for c in word:
            if c in VOWELS:
                return c

我需要编写一个可以处理以多个辅音开头的单词的 piglatin 翻译器。

例如,当我输入“字符串”时,我当前得到的输出是:

PigLatin("string") = tringsay

我想要输出:

PigLatin("string") = ingstray

为了写这个,我写了一个额外的函数来遍历单词并找到第一个元音,但之后我不知道如何继续。任何帮助,将不胜感激。

4

3 回答 3

1

找到第一个元音后,通过 do 获取其在字符串中的索引word.index(c)。然后,将整个单词从开头切到元音的索引处

使用该切片,将其放在单词的末尾并添加'ay',就像您在第一个函数中所做的那样。

于 2013-10-01T01:43:32.003 回答
0

您需要找到辅音的索引并对其进行切片。

这是一个例子:

def isvowel(letter): return letter.lower() in "aeiou"

def pigLatin(word):
    if isvowel(word[0]):     # if word starts with a vowel...
        return word + "hay"  # then keep it as it is and add hay to the end
    else:
        first_vowel_position = get_first_vowel_position(word)
        return word[first_vowel_position:] + word[:first_vowel_position] + "ay"

def get_first_vowel_position(word):
    for position, letter in enumerate(word):
        if isvowel(letter):
            return position
    return -1
于 2013-10-01T03:28:54.137 回答
0

可能有更雄辩的方法可以做到这一点,但这是我的解决方案。希望它有帮助!

def pigLatin(aString):
    index = 0
    stringLength = len(aString)
    consonants = ''

    # if aString starts with a vowel then just add 'way' to the end
    if isVowel(aString[index]): 
        return aString + 'way' 
    else:
    # the first letter is added to the list of consonants
        consonants += aString[index]
        index += 1

        # if the next character of aString is a vowel, then from the index 
        # of the vowel onwards + any consonants + 'ay' is returned
        while index < stringLength:
            if isVowel(aString[index]):
                return aString[index:stringLength] + consonants + 'ay'
            else:
                consonants += aString[index]
                index += 1
        return 'This word does contain any vowels.'

def isVowel(character):
    vowels = 'aeiou'
    return character in vowels
于 2013-11-30T19:36:01.280 回答