我是编程的新手,我被分配了一项将英文文本转换为 Pig Latin 的家庭作业。
我目前的代码是:
VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")
def vowel_start(word):
pig_latin = word + "ay"
return pig_latin
def vowel_index(word):
for i, letters in enumerate(word):
if letters in VOWELS:
vowel_index = i
pig_latin = word[vowel_index:] + word[:vowel_index] + "ay"
return pig_latin
else:
pig_latin = word #The issue here is that even if the word
return pig_latin #has vowels, the program will still only
#return the untranslated word as shown
#in else.
english_text = raw_input("What do you want to translate?")
translate = english_text.split()
pig_latin_words = []
translated_text = "".join(str(pig_latin_words)) #The issue here is that the list
#will not join with the string.
for i in translate:
first = i[0]
vow = False
if first in VOWELS:
vow = True
if vow == True:
pig_latin_words.append(vowel_start(i))
else:
pig_latin_words.append(vowel_index(i))
print "The text you translated is " + english_text
print "The translated text is " + translated_text #The issue here is that the program
#displays "The translated text is "
#and that's it
如果我注释掉 def vowel_index 函数的 else 方面,那么 if 方面 然后工作。如果我将它留在程序中,则 if 方面将不再起作用。 过去几天我一直在尝试解决这个问题,但我不知道如何解决。 任何帮助将不胜感激,谢谢!
有关作业的更多详细信息:
- 如果单词以元音开头,则保留单词原样并在末尾添加“ay”。
- 如果单词包含元音,但不在开头,则取元音之前的字母 元音,移到词尾,在词尾加“ay”。
- 如果单词不包含任何元音,则保留单词原样。
最佳答案
您的函数当前的编写方式,您将始终根据第一个字符是否为元音字母在 for 循环的第一次迭代中返回。您需要遍历每个字符,并且只有在所有字符都不是元音字母的情况下才返回不变的单词。
首先删除 else
;当您看到一个不是元音的字符时,您不想返回,因为后面的字符可能是元音。现在因为你有一个 return
在您的 if
中声明,你知道如果你到达循环末尾而不返回 word
中的任何字符是一个元音字母,因此您可以在 for 循环之外不加改变地返回单词。例如:
def vowel_index(word):
for i, letters in enumerate(word):
if letters in VOWELS:
vowel_index = i
return word[vowel_index:] + word[:vowel_index] + "ay"
return word
对于您的第二期,这里发生了几件事。
首先,你需要移动translated_text
的创建所以它在pig_latin_words
之后已经有了新词。这将恰好在您最后的打印语句之前。
此外,要将单词列表转换为由空格分隔的单个字符串,您应该使用以下命令:
translated_text = " ".join(pig_latin_words)
这是一个显示差异的简短示例:
>>> pig_latin_words = ['atcay', 'ogday']
>>> print "".join(str(pig_latin_words)) # your version
['atcay', 'ogday']
>>> print " ".join(pig_latin_words) # my version
atcay ogday
关于python - (Python) If Else 问题和列表到字符串转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15095600/