Python 3 猪拉丁文句子

0 投票
2 回答
641 浏览
提问于 2025-04-18 01:16

我成功做了一个单词翻译的功能,看到班上其他同学的做法,我知道在句子函数里需要把句子分开。但我不知道该怎么处理这些分开的部分!我参考了这个链接 http://www.mit.edu/~johnp/6.189/solutions/piglatin.py(不过是Python 2的),到目前为止我都能理解,但在处理list_of_words之后我就完全迷糊了。是的,我看过其他关于猪拉丁文的问题,但我觉得我连该往哪个方向走都搞不清楚。

抱歉,这个要求有点大,我不想你直接回答我的问题,我只是想知道接下来该怎么做。

consonants = "bcdfghjklmnpqrstvwxyz"

def pig_latinify_word(word):
    fist_letter = str(word[0])
    if first_letter in consonants:
        return str((word[1:] + word[0] + "ay".lower())) #I think the str() is
    else: return str((word + "way".lower())) #arbitrary, but not sure. Being safe!

def pig_latinify_sentence(sentence):
    list_of_words = sentence.split()
    new_sentence = "" #the bit where I am stuck. Understand up to this point.
    for word in list_of_words:
        new_sentence = new_sentence + pig_latinify_word(word)
        new_sentence = new_sentence + ""
return new_sentence

piglatin = pig_latinify_sentence("This is a about to be a piglatin sentence")
print(piglatin)

抱歉如果这只是个烦人的重发,但我看过几个答案,还是不知道接下来该怎么做。另外,我想补充一下,我的一位辅导老师说我不需要分开辅音,但在其他例子中我看到的都是这样。这个可能有关系吗?我不知道!无论如何,谢谢。

编辑:我想我可能找到了一些答案,告诉我接下来需要改什么,但我还是不明白。另外,被建议去查一下课本也没问题。我只是想读懂,我知道这可能有点过分要求。

编辑:天哪,我刚意识到这是个打字错误。是fist_letter,不是first_letter。

谢谢你!我会再读一遍你的回答。

2 个回答

0

你提供的代码可以用 " ".join内置的 map() 函数来重写,这样会更简洁。

def pig_latinify_sentence(sentence):
    return " ".join(map(pig_latinify_word, sentence.split()))

如果你想在句子中考虑标点符号,可以 使用 re 模块

0

当你这样写的时候:

newSentence = ""

你是在把newSentence的类型设定为字符串,这样更容易理解。然后在for循环中,你把猪拉丁语的单词加到新句子里,并且加一个空格。我还要提一下,使用下面这种写法是个好习惯:

newSentence +=  pig_latinify_word(word)
newSentence += " "

因为这段代码是一样的,只是让一切变得更简洁。/=*=-=也是同样的道理。

撰写回答