我正在尝试用Python创建一个猪拉丁语函数,它接受一个单词并返回它的猪拉丁语翻译。您可以将所有辅音转换为第一个元音直到单词的结尾,然后添加" ay",例如' hello'变成了'ellohay'。 这是我的代码:
def pig_latin(word):
""" Returns the pig latin translation of a word. """
i=0
new_word = word
vowel = ["a", "e","i","o","u"]
while word[i] not in vowel:
word[i] = consonant
new_word = new_word[(i+1):] + consonant
i+=1
final_word = new_word + "ay"
return final_word
当我运行它时,它会给出:
NameError:name'辅音'未定义
我真的很感激这方面的帮助。
谢谢!
答案 0 :(得分:0)
在你的while循环中你有word[i] = consonant
。由于这是第一次使用consonant
,因此它不能位于作业的右侧。你只需要切换它即可工作。
consonant = word[i]
(你的功能似乎适用于以辅音开头的单词,但是用元音开头的单词测试它。我不确定猪拉丁的规则是什么。)
答案 1 :(得分:0)
尝试这个。可能可以帮助您进行一些修改。
def pig_latin(s):
n = len ( s )
if ( s[0] == 'a' or s[0] == 'e' or s[0] == 'i' or s[0] == 'o' or s[0] == 'u'):
s = s + 'way'
return s
else:
t = s[0]
s = s + t + 'ay'
return s[1:n+3]
答案 2 :(得分:0)
def main():
lst = ['sh', 'gl', 'ch', 'ph', 'tr', 'br', 'fr', 'bl', 'gr', 'st', 'sl', 'cl', 'pl', 'fl']
sentence = input('Type your sentence or word for convert it into Pig-Latin: ')
sentence = sentence.split()
for k in range(len(sentence)):
i = sentence[k]
if i[0] in ['a', 'e', 'i', 'o', 'u']:
sentence[k] = i+'ay'
elif t(i) in lst:
sentence[k] = i[2:]+i[:2]+'ay'
elif i.isalpha() == False:
sentence[k] = i
else:
sentence[k] = i[1:]+i[0]+'ay'
return ' '.join(sentence)
def t(str):
return str[0]+str[1]
if __name__ == "__main__":
x = main()
print(x)