基本的猪拉丁语翻译麻烦

时间:2018-03-11 11:42:53

标签: python python-3.x

我正在做一个非常简陋的猪拉丁转换器:

def pigLatin (): 
    eng = ""
    pig = ""
    movetoend = ""
    index = 0
    vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
    while eng != "Quit this program":
        eng = input("input english: ")
        pig = ""
        movetoend = ""
        listeng = eng.split()
        if eng == "Quit this program":
            break
        for word in listeng:
            length = len(word)
            movetoend = ""
            if word[0] not in vowels:
                for l in word:
                    if l not in vowels:
                        movetoend = movetoend + l
                        index = index + 1
                    else:
                        break
                pig = pig + " " + word[index:length] + movetoend + "ay"

            elif word[0] in vowels:
                pig = pig + " " + eng[1:length] + "hay"
        print("pig latin is: " + pig)
    print("program closed")

为什么这只适用于我输入的第一个单词?例如我输入“测试测试”并且输出是“esttay sttay ttay”,我不明白为什么它会逐渐恶化? (第一个测试输出是正确的,但其他两个不是

1 个答案:

答案 0 :(得分:0)

您不重启索引。添加行:

index = 0

在最外面的for循环的第一行。并且几乎没有不必要的线条。您如何看待这样的重构?

def pigLatin ():
    # work also with vowels = "aeiouAEIOU"
    vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}

    eng = input("input english: ")

    while eng != "Quit this program":
        pig = ""
        for word in eng.split():
            index = 0
            movetoend = ""
            if word[0] not in vowels:
                for l in word:
                    if l not in vowels:
                        movetoend = movetoend + l
                        index = index + 1
                    else:
                        break
                # slicing without last index makes slice till end of string
                pig = pig + " " + word[index:] + movetoend + "ay"

            elif word[0] in vowels:
                # slicing without last index makes slice till end of string
                pig = pig + " " + eng[1:] + "hay"
        print("pig latin is: " + pig)

        eng = input("input english: ")

    print("program closed")