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翻译器。
例如,当我输入“string”时,我当前得到的输出是:
PigLatin("string") = tringsay
我想要输出:
PigLatin("string") = ingstray
为了写这个,我写了一个额外的函数来遍历单词并找到第一个元音,但之后我不知道如何继续。 任何帮助将不胜感激。
答案 0 :(得分:1)
找到第一个元音后,通过word.index(c)
获取字符串中的索引。然后,将整个单词从开头切换到元音的索引
使用该切片,将其放在单词的末尾并添加'ay'
,就像在第一个函数中一样。
答案 1 :(得分: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
答案 2 :(得分: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