猪句Python翻译

2024-04-27 00:48:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个程序来替换一个句子中的单词,翻译成猪拉丁语(老师不关心元音,只关心大写),我似乎无法让它工作。这是我写的代码。你知道吗

def PiggySentence():
    sentence=str(input("Please enter the sentence you would like converted 
    to Pig Latin: "))
    sentence.split()
    caps ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    for word in sentence:
        if word[0] in caps:
            word = word[1].upper() + word[2:] + word[0].lower() + "ay"

        else:
            word = word[1:] + word[0] + "ay"

    sentence = " ".join(sentence)
    print(sentence)




PiggySentence()

上面写着

Traceback (most recent call last):
   line 18, in <module>
    PiggySentence()
   line 7, in PiggySentence
    word = word[1].upper() + word[2:] + word[0].lower() + "ay"
IndexError: string index out of range

Tags: in程序line老师caps单词upperlower
2条回答
  1. 这里的问题是word[2]超出了范围,这意味着字符串的长度不足以包含第三个字符。我不确定你想让你的程序如何处理像a这样的小词,不管你是想跳过它们还是仅仅附加一个ay或其他什么。

  2. 在循环中,设置word并不是修改原始数组。您可能需要一个输出变量,可以将翻译的单词添加到其中,例如:

output = []
for word in sentence:
    if word[0] in caps:
        output.append(word[1].upper() + word[2:] + word[0].lower() + "ay")

    else:
        output.append(word[1:] + word[0] + "ay")

sentence = " ".join(output)
  1. sentence.split()放在一个单独的行上并不能做你想做的事情,因为它只返回在每个字符上分割的数组。您希望在每个空间拆分返回值后存储它,因此您希望执行sentence = sentence.split(" ")

首先,你不应该在一个函数中接受输入。 第二,你没有考虑单字母单词。 修改函数以仅在长度大于1时执行Pig拉丁格式设置。你知道吗

像这样的。你知道吗

def PiggySentence():
sentence=str(input("Please enter the sentence you would like converted to Pig Latin: "))
sentence.split()
caps ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for word in sentence:
    if len(word) > 1:
        if word[0] in caps:
            word = word[1].upper() + word[2:] + word[0].lower() + "ay"

        else:
            word = word[1:] + word[0] + "ay"

sentence = " ".join(sentence)
print(sentence)

相关问题 更多 >