以多个辅音开头的单词的piglin翻译程序[Python]

2024-06-01 06:55:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我需要写一个pigltin翻译,可以处理以多个辅音开头的单词。在

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

PigLatin("string") = tringsay

我想要输出:

PigLatin("string") = ingstray

为了写这篇文章,我写了一个附加的函数来遍历这个单词并找到第一个元音,但是之后我不确定如何继续。 任何帮助都将不胜感激。在


Tags: infalsestringreturnifdefit单词
3条回答

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

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

你需要找到辅音的索引,然后切片。在

下面是一个例子:

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

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

对于这个片段,将它放在单词的末尾,并添加'ay',就像您在第一个函数中所做的那样。在

相关问题 更多 >