猪拉丁语到英语的转换

时间:2014-04-05 14:50:19

标签: python wxpython

我们获得了将Pig-Latin转换为英语的任务。因此对于例如我必须编写一个程序来转换猪拉丁语句:iway ovealay omputeracy ienceascay to-i love computer science。我们还假设我们的程序为piglatin.py并将其导入到他们提供的不同程序中。所以你可以看到这就是我所做的。

def toEnglish(s):
   words = s.split(" ") ; # split based on space character
   for word in words:
    if word[-3:] == 'way':
     qq = word[:-3]
     return qq

    elif word[-3:] != 'way':
     x = word[:-2]
     y = x[::-1]
     z = y.index('a')
     rrr = int(z)
     a = y[:rrr]
     d = a[::-1]
     b = y[z+1:]
     rr = b[::-1]
     k = d+rr
     return k

我必须将此导入此程序

import piglatin

choice = input ("(E)nglish or (P)ig Latin?\n")
action = choice[:1]
if action == 'E':
    s = input("Enter an English sentence:\n")
    new_s = piglatin.toPigLatin(s)
    print("Pig-Latin:")
    print(new_s)
elif action =='P':
    s = input("Enter a Pig Latin sentence:\n")
    new_s = piglatin.toEnglish(s)
    print("English:")
    print(new_s)

#You can just ignore the middle part 'E' of the program.

问题是当我将代码运行到这个程序中时,它只会转换我键入的第一个单词。所以如果我输入atabay anamay,我只会得到'bat'而不是'bat man'。

好的,我解决了我的问题。

def toEnglish(s)
    words = s.split(" ") ; # split based on space character
    k = []
    for word in words:
        if word[-3:] == 'way':
            qq = word[:-3]
            k.append(qq)
        elif word[-3:] != 'way':
            x = word[:-2]
            y = x[::-1]
            z = y.index('a')
            rrr = int(z)
            a = y[:rrr]
            d = a[::-1]
            b = y[z+1:]
            rr = b[::-1]
            l = d+rr
            k.append(l)
    return ' '.join(k)

1 个答案:

答案 0 :(得分:0)

return内置函数在现场结束并返回在它之后指定的任何值,任何在从未执行之后发生的代码。您的代码存在的问题是returnfor循环中缩进。因此,您的循环将运行一次并返回您拥有的任何值。相反,您可能希望return在所有单词被解密后返回值。因此,您应该将return放在与for循环相同的缩进级别之后。这是有效的代码:

def toEnglish(s):
    words = s.split(" ") ; # split based on space character
    k = []
    for word in words:
        if word[-3:] == 'way':
            qq = word[:-3]
            k.append(qq)
        elif word[-3:] != 'way':
            x = word[:-2]
            y = x[::-1]
            z = y.index('a')
            rrr = int(z)
            a = y[:rrr]
            d = a[::-1]
            b = y[z+1:]
            rr = b[::-1]
            l = d+rr
            k.append(l)
    return k

>>> print ' '.join(toEnglish('atabay anamay'))
蝙蝠侠